Import CSV files into Excel Import CSV files into Excel vba vba

Import CSV files into Excel


Put the code you recorded in a function, replacing the static file name with a variable, then call that function for each *.csv file in the folder. The get the example below to work you need to save a file with this macro in the same folder as the csv files. For my quick test I had to replace the separator from ; to ,, and to remove the last row .UseListObject = False.

Sub ImportAllCSV()  Dim FName As Variant, R As Long  R = 1  FName = Dir("*.csv")  Do While FName <> ""    ImportCsvFile FName, ActiveSheet.Cells(R, 1)    R = ActiveSheet.UsedRange.Rows.Count + 1    FName = Dir  LoopEnd SubSub ImportCsvFile(FileName As Variant, Position As Range)  With ActiveSheet.QueryTables.Add(Connection:= _      "TEXT;" & FileName _      , Destination:=Position)      .Name = Replace(FileName, ".csv", "")      .FieldNames = True      .RowNumbers = False      .FillAdjacentFormulas = False      .RefreshOnFileOpen = False      .BackgroundQuery = True      .RefreshStyle = xlInsertDeleteCells      .SavePassword = False      .SaveData = True      .AdjustColumnWidth = True      .TextFilePromptOnRefresh = False      .TextFilePlatform = xlMacintosh      .TextFileStartRow = 1      .TextFileParseType = xlDelimited      .TextFileTextQualifier = xlTextQualifierDoubleQuote      .TextFileConsecutiveDelimiter = False      .TextFileTabDelimiter = True      .TextFileSemicolonDelimiter = False      .TextFileCommaDelimiter = False      .TextFileSpaceDelimiter = False      .TextFileOtherDelimiter = ","      .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)      .Refresh BackgroundQuery:=False  End WithEnd Sub