Skip to main content
 

How to quickly batch import multiple csv/text/xml files in Excel?

Author: Sun Last Modified: 2024-08-29

In Excel, you may have tied to save a workbook as csv file, text file or xml file, but have you ever tried to import multiple csv/text/xml files from a folder into a workbook or a worksheet? In this article, I introduce some methods to quickly batch import them.


Import multiple text files from a folder into each worksheets of a workbook with VBA

To import text files from a folder to a workbook, you can use below VBA to quickly handle it.

1. Enable a blank workbook, and press Alt + F11 keys to open Microsoft Visual Basic for Applications window.

2. Click Insert > Module, and paste the VBA to the Module window.

VBA: Import all text files from a folder into a workbook

Sub LoadPipeDelimitedFiles()
'UpdatebyKutoolsforExcel20151214
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\*.txt")
    Do While xFile <> ""
        xCount = xCount + 1
        Sheets(xCount).Select
        With ActiveSheet.QueryTables.Add(Connection:="TEXT;" _
          & xStrPath & "\" & xFile, Destination:=Range("A1"))
            .Name = "a" & xCount
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 437
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = False
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = False
            .TextFileSpaceDelimiter = False
            .TextFileOtherDelimiter = "|"
            .TextFileColumnDataTypes = Array(1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
            xFile = Dir
        End With
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files txt", , "Kutools for Excel"
End Sub

3. Press F5 key or Run button to run the VBA, and select a folder that you want to import the text files from in the popping dialog. See screenshot:

a screenshot of seleting a folder from which you want to import txt files

4. And click OK, and each text file in the selected folder has been imported into one worksheet of the active workbook. See screenshot:

a screenshot showing that each text file in the selected folder has been imported into different worksheets of the current workbooka screenshot showing that each text file in the selected folder has been imported into different worksheets of the current workbook 2
a screenshot of kutools for excel ai

Unlock Excel Magic with Kutools AI

  • Smart Execution: Perform cell operations, analyze data, and create charts—all driven by simple commands.
  • Custom Formulas: Generate tailored formulas to streamline your workflows.
  • VBA Coding: Write and implement VBA code effortlessly.
  • Formula Interpretation: Understand complex formulas with ease.
  • Text Translation: Break language barriers within your spreadsheets.
Enhance your Excel capabilities with AI-powered tools. Download Now and experience efficiency like never before!

Import multiple csv files from a folder into a single sheet with VBA

To import all the csv files form a folder into a single sheet, you can use below VBA code.

1. Enable a blank worksheet, and press Alt + F11 keys to open Microsoft Visual Basic for Applications window.

2. Click Insert > Module, and paste below VBA into the new Module window.

VBA: Import csv files from a folder into one worksheet

Sub ImportCSVsWithReference()
'UpdatebyKutoolsforExcel20151214
    Dim xSht  As Worksheet
    Dim xWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Set xSht = ThisWorkbook.ActiveSheet
    If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then xSht.UsedRange.Clear
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\" & "*.csv")
    Do While xFile <> ""
        Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
        Columns(1).Insert xlShiftToRight
        Columns(1).SpecialCells(xlBlanks).Value = ActiveSheet.Name
        ActiveSheet.UsedRange.Copy xSht.Range("A" & Rows.Count).End(xlUp).Offset(1)
        xWb.Close False
        xFile = Dir
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files csv", , "Kutools for Excel"
End Sub

3. Press F5 key or click Run button to execute the VBA, and a dialog pops out to select a folder that you want to import all csv files from. See screenshot:

a screenshot of seleting a folder from which you want to import csv files into a single worksheet

4. Click OK, and a dialog pops out to remind you if clear the contents of active worksheet before importing, here I click Yes. See screenshot:

a screenshot of a prompt box reminding that whether you want to clear the existing sheet before importing csv files

After clicking Yes, all csv files in the selected folder are imported into the current sheet, and place data from Column A to right. See screenshot:

a screenshot showing that all csv files in the selcted folder are imported into the current worksheeta screenshot showing that all csv files in the selcted folder are imported into the current worksheet 2

Tip: If you want to place csv files horizontally in a worksheet, you can use below VBA.

Sub ImportCSVsWithReferenceI()
'UpdatebyKutoolsforExcel20151214
    Dim xSht  As Worksheet
    Dim xWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Set xSht = ThisWorkbook.ActiveSheet
    If MsgBox("Clear the existing sheet before importing?", vbYesNo, "Kutools for Excel") = vbYes Then
        xSht.UsedRange.Clear
        xCount = 1
    Else
        xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
    End If
    Application.ScreenUpdating = False
    xFile = Dir(xStrPath & "\" & "*.csv")
    Do While xFile <> ""
        Set xWb = Workbooks.Open(xStrPath & "\" & xFile)
        Rows(1).Insert xlShiftDown
        Range("A1") = ActiveSheet.Name
        ActiveSheet.UsedRange.Copy xSht.Cells(1, xCount)
        xWb.Close False
        xFile = Dir
        xCount = xSht.Cells(3, Columns.Count).End(xlToLeft).Column + 1
    Loop
    Application.ScreenUpdating = True
    Exit Sub
ErrHandler:
    MsgBox "no files csv", , "Kutools for Excel"
End Sub 

a screenshot of importing csv files horizontally in a worksheet


Import multiple xml files from a folder into a single sheet with VBA

If you want to import all XML files from a folder into a single sheet, you can use below VBA code.

1. Select a blank sheet you want to place the imported data, and press Alt + F11 keys to enable Microsoft Visual Basic for Applications window.

2. Click Insert > Module, paste VBA code into the Module window.

VBA: Import XML files from a folder into a worksheet.

Sub From_XML_To_XL()
'UpdatebyKutoolsforExcel20151214
    Dim xWb As Workbook
    Dim xSWb As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xCount As Long
    On Error GoTo ErrHandler
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder [Kutools for Excel]"
    If xFileDialog.Show = -1 Then
        xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    Application.ScreenUpdating = False
    Set xSWb = ThisWorkbook
    xCount = 1
    xFile = Dir(xStrPath & "\*.xml")
    Do While xFile <> ""
        Set xWb = Workbooks.OpenXML(xStrPath & "\" & xFile)
        xWb.Sheets(1).UsedRange.Copy xSWb.Sheets(1).Cells(xCount, 1)
        xWb.Close False
        xCount = xSWb.Sheets(1).UsedRange.Rows.Count + 2
        xFile = Dir()
    Loop
    Application.ScreenUpdating = True
    xSWb.Save
    Exit Sub
ErrHandler:
    MsgBox "no files xml", , "Kutools for Excel"
End Sub

3. Click Run button or F5 key to run the VBA, and select a folder in the popping dialog, see screenshot:

a screenshot of seleting a folder from which you want to import xml files into a single worksheet

4. Click OK, and all the XML files in the selected folder are imported into the active sheet.


Import or combine multiple xml/csv files into a sheet or a workbook with Kutools for Excel

If you are not familiar with VBA, do worry, here I introduce a handy tool – Kutools for Excel for you. With its powerful Combine utility, you can quickly combine multiple xml files or csv files into one workbook or one Excel sheet.

After installing Kutools for Excel, please do as below:(Free Download Kutools for Excel Now!)

1. Active Excel, and click Kutools Plus > Combine. See screenshot:
a screenshot of enabling the Combine feature of Kutools for Excel

2. And in the step 1 of Combine dialog, choose one separation option as you need. See screenshot:
a screenshot of selecting one operation as you need in the Combine Worksheets wizard

3. Click Next to go to step 2 of the Combine, click Add to add files from various folders or files from one folder to Workbook list, and also you can specify the sheets you want to combine from Worksheet list of right section. See screenshot:
a screenshot of adding files or folders and specifying the sheets you want to combine

4. Click Next to the last one step of Combine, and you can specify the combine options.
a screenshot of specifying the combine options

5. Click Finish, a dialog pops out to remind you select a location to save the new combined result. See screenshot:
a screenshot of selecting a location to save the new combined file

6. Click Save. All adding sheets have been combine into a new single sheet.
a screenshot showing all adding sheets have been combined into a new single worksheet

Tip: With Combine, you also can combine multiple CSV files form multiple folders or one folder into one sheet or workbook.


Export each sheet as csv/text/pdf to a folder with Kutools for Excel

If you want to export each sheet as csv/text/pdf file to a folder, Kutools for Excel’s Split Workbook utility can do a favor for you.

After free downloading and installing Kutools for Excel, please do as below:

1. Enable the workbook you want to export its worksheets, and click Kutools Plus > Workbook > Split Workbook. See screenshot:

a screenshot of enabling the Split Workbook feature

2. In the Split Workbook dialog, you can check the sheet names you need to export, in default all the sheets are checked, and check Specify save format and select the file format you want to save as from below drop down list. See screenshot:

a screenshot of checking the sheet names you will export and specifying a save format

3. Click Split and select a folder that to save the split files in the Browse for Folder dialog, see screenshot:

a screenshot of selecting a destination folder to save the exported files

4. Click OK, now all the checked sheets are exported as new file format in the selected folder.


Relative Articles:


Best Office Productivity Tools

🤖 Kutools AI Aide: Revolutionize data analysis based on: Intelligent Execution   |  Generate Code  |  Create Custom Formulas  |  Analyze Data and Generate Charts  |  Invoke Kutools Functions
Popular Features: Find, Highlight or Identify Duplicates   |  Delete Blank Rows   |  Combine Columns or Cells without Losing Data   |   Round without Formula ...
Super Lookup: Multiple Criteria VLookup    Multiple Value VLookup  |   VLookup Across Multiple Sheets   |   Fuzzy Lookup ....
Advanced Drop-down List: Quickly Create Drop Down List   |  Dependent Drop Down List   |  Multi-select Drop Down List ....
Column Manager: Add a Specific Number of Columns  |  Move Columns  |  Toggle Visibility Status of Hidden Columns  |  Compare Ranges & Columns ...
Featured Features: Grid Focus   |  Design View   |   Big Formula Bar    Workbook & Sheet Manager   |  Resource Library (Auto Text)   |  Date Picker   |  Combine Worksheets   |  Encrypt/Decrypt Cells    Send Emails by List   |  Super Filter   |   Special Filter (filter bold/italic/strikethrough...) ...
Top 15 Toolsets12 Text Tools (Add Text, Remove Characters, ...)   |   50+ Chart Types (Gantt Chart, ...)   |   40+ Practical Formulas (Calculate age based on birthday, ...)   |   19 Insertion Tools (Insert QR Code, Insert Picture from Path, ...)   |   12 Conversion Tools (Numbers to Words, Currency Conversion, ...)   |   7 Merge & Split Tools (Advanced Combine Rows, Split Cells, ...)   |   ... and more

Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time.  Click Here to Get The Feature You Need The Most...


Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!