VBA Save As CSV File is Overwritten by First Sheet - excel

I have workbook, I loop through and save each sheet as a csv. The problem is when the loop finishes Excel prompts me to save. If I click "Save", then last worksheet is overwritten with whichever sheet the excel workbook opens on.
If click "Don't Save" everything remains saved with the proper data, but I can't rely on the user to click "Don't Save" every time so I need to find where my code is over writing the data when saved.
How do I keep my csv sheet from being overwritten?
Sub LipperFormat()
'Create Workbook
Dim wb As Workbook
'Get FilePath
Dim wbActive As Workbook
Set wbActive = ActiveWorkbook
Dim wsActive As Worksheet
Set wsActive = wbActive.Worksheets(1)
'Get File Path
Dim filePath As String
Dim rngActive As Range
Set rngActive = wsActive.Cells(1, 2)
filePath = rngActive.Value
'Open File
Set wb = Workbooks.Open(filePath)
'Create Copy of file and CSV
Dim copyFilePath As String
Dim fileExtension As String: fileExtension = "_OG.xlsx"
copyFilePath = Left(filePath, Len(filePath) - 5) + fileExtension
wb.SaveCopyAs copyFilePath
'Loop through worksheets
Dim WS_Count As Integer
Dim i As Integer
WS_Count = wb.Worksheets.Count
For i = 1 To WS_Count
Dim col As Integer
Dim ws As Worksheet
Set ws = wb.Sheets(i)
'Save As CSV
Dim sheetName As String: sheetName = ws.Name
Dim csvFilePath As String
Dim csvSheet As Worksheet
cvsFilePath = Left(filePath, Len(filePath) - 5) + "__" + sheetName
'ws.Name = sheetName
ws.SaveAs FileName:=cvsFilePath, FileFormat:=xlCSV, CreateBackup:=False
Next i
'wb.Save
wb.Close
End Sub

You code is too large for no benefits. I cleaned it and corrected your mistakes and also added necessary pieces to not ask the users for anything:
Sub LipperFormat()
Dim filePath As String
Dim csvFileName As String
Dim ws As Worksheet
Dim wb As Workbook
Application.DisplayAlerts = False
'define parameters
Set wb = ThisWorkbook
Set ws = wb.Worksheets(1) 'it is better to define it with the name, not with its index
filePath = ws.Cells(1, 2).Value
'Open File
Set wb = Workbooks.Open(Filename:=filePath, ReadOnly:=True)
'loop and save as csv
For Each ws In wb.Worksheets
csvFileName = wb.Path & "\" & Left(wb.Name, Len(wb.Name) - 5) & "__" & ws.Name
ws.Copy
ActiveWorkbook.SaveAs Filename:=csvFileName, FileFormat:=xlCSV, CreateBackup:=True
ActiveWorkbook.Close
Next ws
'close WB
wb.Close
Application.DisplayAlerts = True
End Sub

Related

Copy the content of multiple Excel files which are inside a folder and paste it in the same worksheet that is executing the macro

The code I have below does more or less that what title says but every time it reads one file creates a new worksheet and pastes the content there
Code
Sub fileLoop()
Dim mypath As String, myfile As String
mypath = "C:\Users\xxxx\Desktop\test macro\"
myfile = Dir(mypath & "*.xlsx")
Dim ws As Worksheet
Do While myfile <> ""
Dim wb As Workbook
Set wb = Workbooks.Open(mypath & myfile)
Set ws = wb.Sheets(1)
For Each ws In wb.Worksheets
ws.Copy after:=ThisWorkbook.ActiveSheet
Next
wb.Close
myfile = Dir
Loop
End Sub
Files I have
What I get
What I need
I tried changing this line to get the content of files in the same worksheet
For Each ws In wb.Worksheets
ws.Copy after:=ThisWorkbook.ActiveSheet
Next
Change ws.Copy after:=ThisWorkbook.ActiveSheet
To ws.UsedRange.Copy ActiveSheet.Cells(ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row + 1,1)
Also the Set ws = wb.Sheets(1) is useless because you are just resetting it without use in the very next statement!
Try playing around with this:
Option Explicit
Sub fileLoop()
Dim mypath As String, myfile As String
mypath = "C:\Users\xxxx\Desktop\test macro\"
myfile = Dir(mypath & "*.xlsx")
Dim ws As Worksheet
Dim wb As Workbook
Dim rngTarget As Range
Dim numRows As Integer
Set rngTarget = ThisWorkbook.Worksheets("Hoja1").Range("A2:M2")
Do While myfile <> ""
Set wb = Workbooks.Open(mypath & myfile)
For Each ws In wb.Worksheets
numRows = ws.Range("A1").Offset(Rows.Count - 1).End(xlUp).Row
rngTarget.Resize(numRows).Value = ws.Range("A2:M2").Resize(numRows).Value
Set rngTarget = rngTarget.Offset(numRows)
Next ws
wb.Close
myfile = Dir
Loop
Set rngTarget = Nothing
Set wb = Nothing
End Sub

Copy worksheet from different workbook to this workbook reference problems

I have two Excel Files in the same folder. The macro runs on the master workbook (wb_master). It should copy the sheet from the Data Workbook (wb_Data) to wb_master.
My attempt is this:
Dim wb_name as String
Dim wb_master as Object
Dim ws_master as Object
Dim wb_Data As Object
Dim MyPath as String
Dim DataFile as String
wb_name = ActiveWorkbook.Name 'other users could have renamed the wb, so I don't want to refer to the name with a fixed string
Set wb_master = Workbooks(wb_name)
Set ws_master = wb_master.Worksheets(1)
MyPath = ActiveWorkbook.Path
DataFile = Dir(MyFolder & "\Data_*.xlsx")
Set wb_Data = Workbooks.Open(FileName:=MyPath & "\" & DataFile)
wb_Data.Sheets(1).Copy After:=wb_master.Sheets(1)
wb_Data.Close SaveChanges:=False
The problem with this is, that in the line where it copies wb_Data.Sheets(1) it doesn't use the wb_master workbook, but the wb_data workbook as destination. I assume this is because when wb_master is called, it reevaluates the ActiveWorkbook, which at this point is wb_Data.
However even though I understand, why this is happening, I can't find a solution to the problem.
Edit: This macro runs in the personal.xslb
Copy Sheet From a Closed Workbook
If you run the code from the Personal.xslb, then replace ThisWorkbook with ActiveWorkbook or the appropriate workbook e.g. Workbooks("Master.xlsm").
Option Explicit
Sub CopySheet()
Dim dwb As Workbook: Set dwb = ThisWorkbook ' workbook containing this code
Dim FolderPath As String: FolderPath = dwb.Path & "\"
Dim swbName As String: swbName = Dir(FolderPath & "Data_*.xlsx")
If Len(swbName) = 0 Then Exit Sub ' file not found
Dim sFilePath As String: sFilePath = FolderPath & swbName
Dim swb As Workbook: Set swb = Workbooks.Open(sFilePath)
Dim ssh As Object: Set ssh = swb.Sheets(1)
ssh.Copy After:=dwb.Sheets(1) ' second sheet
'ssh.Copy Before:=dwb.Sheets(1) ' first sheet
'ssh.Copy After:=dwb.Sheets(dwb.Sheets.Count) ' last sheet
swb.Close SaveChanges:=False
MsgBox "Sheet copied.", vbInformation
End Sub

Column number - copying and pasting from file to another file

I have a little problem with my code. I want to copy my data from one file to my main file. When I check the code I meet with one problem. The code works fine until copied. In this line
Set cell1 = wsDest.Cells(1, Range("B1").End(xlToRight).Column + 1)
the cell is selected from the file from I am taking the data and not the folder I am pasting into.
I want my data to paste from these other files into the main file. I want to add them as columns, not rows.
Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")
mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
strFile = Dir(strFolder & "*.xls*")
Do While strFile <> ""
Set newWb = Workbooks.Open(strFolder & strFile)
Set newWs = newWb.Sheets(1)
strFile = Dir
newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
newWs.Columns(ActiveCell.Column).EntireColumn.Delete
newWs.Range("B1", Range("B1").End(xlDown).End(xlToRight)).Copy _
mainWs.Range("P1")
Loop
End Sub
You have to declare which file/sheet is which. Each line should refer to the right worksheet. All lines starting with cell or range should have worksheet first like: "mainWs.Cell".
In the new file you have not declared any worksheet, only workbook (wb).
I haven't tryed the code below, but I hope it unlocks your problem thinking.
Good luck!
Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Dim strFile As String
Dim cell1 As Range
Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")
mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
'in my main file I delete the last column only one
strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
strFile = Dir(strFolder & "*.xls*")
Do While strFile <> ""
Set newWb = Workbooks.Open(strFolder & strFile)
'Set the sheet you want to use, using "first sheet" or sheet by name
'Set newWs = newWb.Sheets(1)
'Set newWs = newWb.Worksheets("Worksheet1")
strFile = Dir
newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
newWs.Columns(ActiveCell.Column).EntireColumn.Delete
'Set cell1 = newWs.Cells(1, Range("B1").End(xlToRight).Column + 1)
newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Copy
'the adress is taking from file when I take the data, not the main file which should take.
mainWs.Range(cell1).PasteSpecial Paste:=xlPasteValues
Loop
End Sub

Combine multiple workbooks to one workbook

I need to combine multiple workbook to one workbook.
Source workbooks have unique sheet name = "job"
Destination workbook have multiple sheets name
The Below code have 2 issues,
For loop not work
pasted data in Destination workbook create a new sheet. But i need to paste the data to existing sheet.
Sub combine()
'destination worksheets
Dim Ar As Worksheet
Dim nr As Worksheet
Set Ar = ThisWorkbook.Sheets("sheetAr")
Set nr = ThisWorkbook.Sheets("Sheetnr")
'Source workbooks
Dim FolderPath As String
Dim Filename As String
Application.ScreenUpdating = False
FolderPath = Environ("userprofile" & "\Desktop\Copy")
Filename = Dir(FolderPath & "*.xlsx*")
Do While Filename <> ""
Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
Dim ws As Worksheet
Dim AW As Workbook
Set AW = ActiveWorkbook
Set ws= ActiveWorkbook.Sheets("Job")
For Each AW In ws
AW.Activate
Cells.ShownAll
ws.Copy Ar
Next AW
Workbooks(Filename).Close savechanges = True
Filename = Dir()
Loop
Application.ScreenUpdating = True
End Sub
FolderPath = Environ("userprofile" & "\Desktop\Copy") should be FolderPath = Environ("userprofile") & "\Desktop\Copy\".For Each AW In ws makes no sense since AW is a workbook and ws a worksheet. You probably meant For Each ws in AW but there is no need to loop if only Job sheet is the source. Workbooks(Filename).Close savechanges = True is missing : but since the workbook was opened read-only there are no change to save so use .Close savechanges := False.
Option Explicit
Sub combine()
Dim wb As Workbook, rng As Range
Dim wsAr As Worksheet, wsSrc As Worksheet
Dim FolderPath As String, Filename As String
Dim iTargetRow As Long, c As Long, n As Long
FolderPath = Environ("userprofile") & "\Desktop\Copy\"
Filename = Dir(FolderPath & "*.xlsx*")
' destination worksheet
Set wsAr = ThisWorkbook.Sheets("sheetAr")
iTargetRow = wsAr.UsedRange.Row + wsAr.UsedRange.Rows.Count
Application.ScreenUpdating = False
Do While Filename <> ""
Set wb = Workbooks.Open(Filename:=FolderPath & Filename, ReadOnly:=True)
Set wsSrc = wb.Sheets("Job")
Set rng = wsSrc.UsedRange
rng.Copy wsAr.Cells(iTargetRow, rng.Column)
iTargetRow = iTargetRow + rng.Rows.Count
wb.Close savechanges:=False ' opened read only
Filename = Dir()
n = n + 1
Loop
Application.ScreenUpdating = True
MsgBox n & " workbooks scanned", vbInformation
End Sub

copying data from another workbook

i am trying to replace the current data in my file with the data in any another selected file which have same attributes. i want to replace the data from A1:Q in the current file from any other selected file. I tried writing the code but its showing errors .
Sub newdata()
Set appxl = CreateObject("Excel.application")
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
'Open Source File.xlsx
With appxl
vFile = Application.GetOpenFilename(Title:="Select File To Be Opened")
If vFile = False Then Exit Sub 'if the user didn't select a file, exit sub
' Set myfile = Workbooks.Open(vFile)
.Visible = False
End With
'Get first sheet data
Set myfile = appxl.Windows(vFile)
myfile.Activate
Set currentSheet = myfile.Sheets(1)
'Past the table in my current Excel file
lastRow = currentSheet.Range("A1").End(xlDown).Row
Sheets("Data retrieval").Range("A1:E" & lastRow) = currentSheet.Range("A1:Q" & lastRow).Value
'Close Source File.xlsx
appxl.Workbooks(vFile).Close
End Sub
This is not the prettiest of codes but it works just as you asked!
Sub newdata()
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
Dim sourcefileworksheet As String
Dim destinationwb As String
Dim destinationwksheet As String
'set destination worksheet as open workbook when you run macro
destinationwb = ActiveWorkbook.Name
destinationwksheet = ActiveSheet.Name
'Select source file
Dim fNameAndPath As Variant, wb As Workbook
fNameAndPath = Application.GetOpenFilename(Title:="Select File To Be Opened")
' cancel macro if nothing selected
If fNameAndPath = False Then
MsgBox ("Nothing Selected, Macro Cancelled")
Exit Sub
End If
'Open Source File.xlsx
Workbooks.Open (fNameAndPath)
'set source names
sourceFileName = ActiveWorkbook.Name
sourcefileworksheet = ActiveSheet.Name
'Determine last row of source
lastRow = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1").End(xlDown).Row
'Past the table in my current Excel file - Note that you should change the range of destination to A1:Q if you want all copied
Workbooks(destinationwb).Worksheets(destinationwksheet).Range("A1:E" & lastRow) = Workbooks(sourceFileName).Worksheets(sourcefileworksheet).Range("A1:Q" & lastRow).Value
'Close Source File.xlsx
Workbooks(sourceFileName).Close
'Confirm complete
MsgBox ("Complete!")
End Sub

Resources