Hi,
I have written a code that is supposed to combine all CSV sheets in a folder to one sheet. The code is running without errors, apart from no data is being copied to the new file. Can somebody find my mistake?
I have written a code that is supposed to combine all CSV sheets in a folder to one sheet. The code is running without errors, apart from no data is being copied to the new file. Can somebody find my mistake?
VBA Code:
Sub CombineCSVSheets()
Dim FolderPath As String
Dim FileName As String
Dim wb As Workbook
Dim ws As Worksheet
Dim wsCombined As Worksheet
Dim LastRow As Long
Dim CurrentRow As Long
' Define the folder path containing the CSV files
FolderPath = "C:\Products\AllProducts"
' Create a new workbook to combine the CSV sheets
Set wb = Workbooks.Add
' Retrieve the first CSV file in the folder
FileName = Dir(FolderPath & "*.csv")
' Loop through all CSV files in the folder
Do While FileName <> ""
' Open the CSV file
Workbooks.Open FileName:=FolderPath & FileName
' Copy each row of data from the CSV sheet to the combined sheet
Set ws = ActiveSheet
Set wsCombined = wb.Worksheets.Add(After:=wb.Worksheets(wb.Worksheets.Count))
ws.Rows(1).Copy wsCombined.Rows(1)
LastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
CurrentRow = wsCombined.Cells(wsCombined.Rows.Count, 1).End(xlUp).Row + 1
ws.Range("A1", "A" & LastRow).Copy wsCombined.Cells(CurrentRow, 1)
' Close the CSV file without saving changes
wb.Worksheets(wsCombined.Name).Delete
wb.Close SaveChanges:=False
' Retrieve the next CSV file in the folder
FileName = Dir
Loop
' Save and close the combined workbook
wb.SaveAs "C:\products\AllProducts\Combined"
wb.Close SaveChanges:=True
End Sub