VBA macros · Workbooks and files
VBA macro to import a CSV file into Excel
Pick a CSV file and import it into a new sheet with the right delimiter, UTF-8 characters and no broken quoted fields. Options for leading zeros and semicolons.
Double-clicking a CSV file lets Excel guess everything: dates get swapped, long numbers lose digits, accented characters turn into symbols and product codes lose their leading zeros. This macro imports a CSV file into a new sheet with settings you control, through the same text-import engine as Data › From Text/CSV in older Excel.
Option Explicit
Sub ImportCsvFile()
Dim filePath As Variant
Dim ws As Worksheet
Dim qt As QueryTable
#If Mac Then
filePath = Application.GetOpenFilename()
#Else
filePath = Application.GetOpenFilename("CSV files (*.csv),*.csv", , "Pick a CSV file")
#End If
If VarType(filePath) = vbBoolean Then Exit Sub ' Cancel
On Error GoTo Fail
Set ws = ActiveWorkbook.Worksheets.Add(After:=ActiveSheet)
Set qt = ws.QueryTables.Add(Connection:="TEXT;" & filePath, Destination:=ws.Range("A1"))
With qt
.TextFileParseType = xlDelimited
.TextFileCommaDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileTabDelimiter = False
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFilePlatform = 65001 ' UTF-8
.TextFileStartRow = 1
.AdjustColumnWidth = True
.RefreshStyle = xlOverwriteCells
.Refresh BackgroundQuery:=False
End With
qt.Delete ' keep the data, drop the query
MsgBox "Imported " & ws.UsedRange.Rows.Count & " row(s).", vbInformation
Exit Sub
Fail:
MsgBox "Import failed: " & Err.Description, vbExclamation
End SubHow to use it
- Open the workbook and press
Alt+F11(Mac:Opt+F11orFn+Opt+F11) to open the VBA editor. See The Developer tab and the VBA editor if you have never used it. - Choose Insert › Module. An empty code window opens on the right.
- Paste the whole code into that window. If the module already starts with
Option Explicit, do not paste that line twice. - Go back to Excel, press
Alt+F8(Mac:Opt+F8, or Tools › Macro › Macros), pickImportCsvFileand click Run. - Save the file as an Excel Macro-Enabled Workbook (.xlsm). A normal .xlsx file throws the code away when you save it.
To have this macro ready in every workbook, keep it in your Personal Macro Workbook (PERSONAL.XLSB). If you do not have one yet, record any tiny macro with Store macro in: Personal Macro Workbook (see The macro recorder: record, read and clean up code), then paste this code into a module under VBAProject (PERSONAL.XLSB). The macro works on whichever workbook is active when you run it.
How it works
Application.GetOpenFilename shows the standard Open dialog but does not open anything; it only returns the chosen path, or False on Cancel. On Windows the filter shows only .csv files. On a Mac the filter argument works differently, so the #If Mac Then branch calls it without one.
QueryTables.Add with a TEXT; connection is the classic text-import engine. Its properties match the steps of the old Text Import Wizard: delimited data, a comma as the separator, double quotes around text (so a field like "Smith, John" stays in one cell), and file origin 65001, which is the code for UTF-8 so letters such as é, ü and ß arrive intact.
Refresh BackgroundQuery:=False runs the import immediately and waits for it to finish. qt.Delete then removes the query definition but leaves the imported data on the sheet, so the sheet is not tied to the file. The new sheet is added after the active one, so earlier imports are never overwritten.
Change it
Typical adjustments, added inside the With qt block before .Refresh:
- European CSV files that use semicolons: set
.TextFileCommaDelimiter = Falseand.TextFileSemicolonDelimiter = True. - Decimal commas:
.TextFileDecimalSeparator = ","and.TextFileThousandsSeparator = ".". - Keep leading zeros and long numbers as text:
.TextFileColumnDataTypes = Array(xlTextFormat, xlGeneralFormat, xlGeneralFormat), one entry per column, starting with column A. - Dates written day-month-year: use
xlDMYFormatfor that column in the same array (xlMDYFormatfor US files,xlYMDFormatfor ISO dates). - Skip a title line above the headings:
.TextFileStartRow = 2.
To name the new sheet after the file, add ws.Name = Left$(Mid$(filePath, InStrRev(filePath, Application.PathSeparator) + 1), 31) after adding it; cut the .csv off if you like. To import every CSV in a folder, combine this with the folder loop from VBA macro to merge all workbooks in a folder into one sheet.
What can go wrong
If every row ends up in column A, the file uses a different separator; open it in Notepad (or TextEdit) to check and switch the delimiter settings. If accented characters look wrong, the file is probably not UTF-8: try .TextFilePlatform = 1252 (Western Windows).
qt.Delete. It is harmless; delete it there if it bothers you.Power Query (Data › From Text/CSV) is the modern way to import files that you load again and again, because it remembers every step. The macro is best for quick one-off imports with exact settings.
Related: VBA macro to merge all workbooks in a folder into one sheet, VBA macro to list all files in a folder in Excel, Files and folders: open, save, loop through files and write text files.