Skip to content

Instantly share code, notes, and snippets.

@luizs81
Last active October 26, 2022 19:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luizs81/a03df776b983fa20f935 to your computer and use it in GitHub Desktop.
Save luizs81/a03df776b983fa20f935 to your computer and use it in GitHub Desktop.
Import all CSV files from a folder into one Excel file, but separated sheets
Sub MergeCSV()
'Author: Jerry Beaucaire
'Date: 8/16/2010
'Summary: Import all CSV files from a folder into separate sheets
' named for the CSV filenames
'Update: 2/8/2013 Macro replaces existing sheets if they already exist in master workbook
Dim fpath As String
Dim fCSV As String
Dim wbCSV As Workbook
Dim wbMST As Workbook
Set wbMST = ThisWorkbook
'Dim fpath As Variant
fpath = InputBox("Path to the folder where the CSV files are:" & vbNewLine & "(Include backslash in the end)")
Application.ScreenUpdating = False 'speed up macro
Application.DisplayAlerts = False 'no error messages, take default answers
fCSV = Dir(fpath & "*.csv") 'start the CSV file listing
On Error Resume Next
Do While Len(fCSV) > 0
Set wbCSV = Workbooks.Open(fpath & fCSV) 'open a CSV file
wbMST.Sheets(ActiveSheet.Name).Delete 'delete sheet if it exists
ActiveSheet.Move After:=wbMST.Sheets(wbMST.Sheets.Count) 'move new sheet into Mstr
Columns.AutoFit 'clean up display
fCSV = Dir 'ready next CSV
Loop
Application.ScreenUpdating = True
Set wbCSV = Nothing
End Sub
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment