Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel Import Multiple Text Files to Multiple Sheets

· 6 min read · Home Tech

In this article
  1. Why You Might Need This
  2. How the VBA Macro Works
  3. Choosing the Right Import Method
  4. Common Problems and How to Fix Them
  5. Power Query Alternative: When to Use It
  6. Safety and Accuracy Tips
  7. Frequently Asked Questions

Yes, you can import multiple text files into separate sheets in Excel, and the most reliable way is to use a VBA macro that loops through the files. This article explains the exact steps, the code you need, and how to handle common issues like inconsistent delimiters or file naming.

Why You Might Need This

When you receive daily sales reports, server logs, or sensor data as separate .txt or .csv files, opening each one manually and copying the data into a new sheet is tedious and error-prone. A macro automates the process: you select the folder, and Excel creates a new sheet for every text file, names the sheet after the file, and imports the data. This is especially useful for recurring tasks—run it once, and every future batch of files is imported consistently.

How the VBA Macro Works

The macro uses the Workbooks.OpenText method, which is the same engine behind Excel's Text Import Wizard. It opens each file, copies the contents, pastes them into a new sheet in your main workbook, and closes the source file. The key is the Dir function, which loops through all files in a folder that match a pattern (like *.txt).

Here is the core code. Press Alt+F11 to open the VBA editor, insert a new module, and paste this:

Sub ImportAllTextFiles()
    Dim FolderPath As String
    Dim Filename As String
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim LastRow As Long

    ' Change this path to your folder
    FolderPath = "C:\YourFolder\"
    Filename = Dir(FolderPath & "*.txt")

    Application.ScreenUpdating = False

    Do While Filename <> ""
        ' Create a new sheet named after the file (clean invalid characters)
        Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        ws.Name = Left(Filename, 31)  ' Sheet names max 31 chars

        ' Open the text file and copy its contents
        Workbooks.OpenText Filename:=FolderPath & Filename, _
            DataType:=xlDelimited, _
            Comma:=True, _
            Tab:=True
        Set wb = ActiveWorkbook
        wb.Sheets(1).UsedRange.Copy ws.Range("A1")
        wb.Close SaveChanges:=False

        Filename = Dir  ' Get next file
    Loop

    Application.ScreenUpdating = True
End Sub

This code assumes your files use commas or tabs as delimiters. If your files use a different delimiter (like semicolons or pipes), adjust the Comma and Tab arguments—set them to True or False as needed.

Choosing the Right Import Method

There are three main ways to import multiple text files, and each has trade-offs:

  • Power Query (Get & Transform) – You can combine multiple files from a folder into one table, but splitting them into separate sheets requires additional steps (like grouping by file name). It's great for merging, but not ideal for one-sheet-per-file.
  • VBA Macro – The most flexible and direct. It gives you full control over sheet naming, formatting, and error handling. Works in all desktop versions of Excel.
  • Manual Copy-Paste – Fine for a one-off with 2-3 files, but impractical for dozens.

For a true “one file → one sheet” result, VBA is the standard solution.

Common Problems and How to Fix Them

Here are the issues you'll likely encounter, with solutions:

  • Sheet name too long or contains invalid characters – Excel sheet names are limited to 31 characters and cannot contain \ / ? * [ ] :. Use Left(Filename, 31) and replace invalid characters with Replace.
  • Files have different delimiters – If some files use commas and others use tabs, you can either set both Comma:=True and Tab:=True (Excel will treat both as delimiters), or use the Format parameter to detect the delimiter automatically.
  • Data has leading zeros (like ZIP codes) – The macro imports as text, so leading zeros are preserved. If you need them as numbers, you'll lose the zeros—that's a data-type decision.
  • Files are in subfolders – The Dir function only looks in the top-level folder. To include subfolders, you need a recursive loop.
  • Macro is slow with many files – Turn off screen updating (Application.ScreenUpdating = False) and calculation (Application.Calculation = xlCalculationManual) to speed it up.

Power Query Alternative: When to Use It

Power Query (available in Excel 2016 and later) is a better choice if you want to combine all files into a single table, or if you need to refresh the data when new files are added. To import multiple files into separate sheets with Power Query, you would:

  1. Go to Data → Get Data → From File → From Folder.
  2. Browse to your folder and click Combine & Transform Data.
  3. In the Power Query editor, you'll see a table with a column for the file name and a column with the file contents.
  4. Add a custom column that extracts the file name, then group by that column.
  5. Load each group to a new worksheet using a script or by splitting the query.

This is more complex than VBA for the “separate sheets” use case, but it's non-destructive and easier to maintain if your data sources change.

Safety and Accuracy Tips

Before running any macro, save your workbook. The macro creates new sheets and overwrites any sheet with the same name (it will throw an error if a sheet name already exists). To avoid data loss, add a line to check if the sheet exists and delete it first, or add a unique timestamp to sheet names.

Also, test on a small sample folder first. Verify that the import handles:

  • Empty files (they will create a blank sheet)
  • Files with different column counts
  • Files with headers or without headers

If your files have headers, you might want to skip the first row or copy it only once. The macro above copies everything, so you'll get the header in every sheet—which is usually what you want.

Frequently Asked Questions

Can I import .csv files the same way?

Yes, just change the file pattern in the Dir function from *.txt to *.csv. CSV files are text files with commas, so the same macro works.

How do I make the macro ask for a folder each time?

Use the FileDialog object to let the user pick a folder. Replace the hard-coded FolderPath with:

Dim fd As FileDialog
Set fd = Application.FileDialog(msoFileDialogFolderPicker)
If fd.Show = -1 Then
    FolderPath = fd.SelectedItems(1) & "\"
Else
    Exit Sub
End If

What if my files use semicolons as delimiters?

Set Comma:=False and add Semicolon:=True to the OpenText parameters. For example: Semicolon:=True.

Can I import files from a specific subfolder only?

Yes, modify the FolderPath to include the subfolder path, or use a recursive function to loop through all subfolders.

Why does my macro stop with an error about a sheet name?

This happens when the file name is longer than 31 characters or contains characters like : or ?. Use Left(Filename, 31) and replace invalid characters with Replace to fix it.

Is there a way to do this without VBA?

If you have Excel 365, you can use Power Query to combine files and then use a formula to split them into separate sheets, but it's not straightforward. VBA is the most reliable method for a true one-file-per-sheet result.