Tip: Other languages are Google-Translated. You can visit the English version of this link.
Log in
x
or
x
x
Register
x

or

How to import multiple text files from a folder into one worksheet?

For instances, here you have a folder with multiple text files, what you want to do is to import these text files into a single worksheet as below screenshot show. Instead of copying the text files one by one, are there any tricks to quickly import the text files from one folder into one sheet?

Import multiple text files from one folder into a single sheet with VBA

Import text file to the active cell with Kutools for Excel good idea3


goodExport Range to File

Kutools for Excel's Export Range to File function can export or save a range to separate file as
workbook, pdf, text, csv or text.
Click Enterprise > Import/Export > Export Range to File.
doc export cell range to file
Office Tab Enable Tabbed Editing and Browsing in Office, and Make Your Work Much Easier...
Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%
  • Reuse Anything: Add the most used or complex formulas, charts and anything else to your favorites, and quickly reuse them in the future.
  • More than 20 text features: Extract Number from Text String; Extract or Remove Part of Texts; Convert Numbers and Currencies to English Words.
  • Merge Tools: Multiple Workbooks and Sheets into One; Merge Multiple Cells/Rows/Columns Without Losing Data; Merge Duplicate Rows and Sum.
  • Split Tools: Split Data into Multiple Sheets Based on Value; One Workbook to Multiple Excel, PDF or CSV Files; One Column to Multiple Columns.
  • Paste Skipping Hidden/Filtered Rows; Count And Sum by Background Color; Send Personalized Emails to Multiple Recipients in Bulk.
  • Super Filter: Create advanced filter schemes and apply to any sheets; Sort by week, day, frequency and more; Filter by bold, formulas, comment...
  • More than 300 powerful features; Works with Office 2007-2019 and 365; Supports all languages; Easy deploying in your enterprise or organization.


Here is a VBA code can help you import all text files from one specific folder into a new sheet.

1. Enable a workbook you want to import text files, and press Alt + F11 keys to enable Microsoft Visual Basic for Applications window.

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

VBA: Import multiple text files from one folder to one sheet

Sub Test()
'UpdatebyExtendoffice6/7/2016
    Dim xWb As Workbook
    Dim xToBook As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xFiles As New Collection
    Dim I As Long
    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
    If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
    xFile = Dir(xStrPath & "*.txt")
    If xFile = "" Then
        MsgBox "No files found", vbInformation, "Kutools for Excel"
        Exit Sub
    End If
    Do While xFile <> ""
        xFiles.Add xFile, xFile
        xFile = Dir()
    Loop
    Set xToBook = ThisWorkbook
    If xFiles.Count > 0 Then
        For I = 1 To xFiles.Count
            Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
            xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
            On Error Resume Next
            ActiveSheet.Name = xWb.Name
            On Error GoTo 0
            xWb.Close False
        Next
    End If
End Sub

3. Press F5 to display a dialog, and select a folder which contains text files you want to import. See screenshot:
doc import text files from a folder 1

4. Click OK. Then the text files have been imported to the active workbook as new sheet separately.
doc import text files from a folder 2


If you want to import one text file to a specific cell or range, you can apply Kutools for Excel’s Insert File at Cursor utility.

Kutools for Excel, with more than 120 handy Excel functions, enhance your working efficiency and save your working time.

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

1. Select a cell you want to import the text file, and click Enterprise > Import/ Export > Insert File at Cursor. See screenshot:
doc import text files from a folder 3

2. Then a dialog pops out, click Browse to display the Select a file to be inserted at the cell cursor position dialog, next select Text Files from the drop down list, and then choose the text file you want to import. See screenshot:
doc import text files from a folder 4

3. Click Open > Ok, and the specify text file has been inserted at the cursor position, see screenshot:
doc import text files from a folder 5


Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails...
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range...
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns... Prevent Duplicate Cells; Compare Ranges...
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select...
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more...
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments...
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic...
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF...
  • More than 300 powerful features. Supports Office/Excel 2007-2019 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial.
kte tab 201905

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!
officetab bottom
Say something here...
symbols left.
You are guest ( Sign Up? )
or post as a guest, but your post won't be published automatically.
Loading comment... The comment will be refreshed after 00:00.
  • To post as a guest, your comment is unpublished.
    302del · 2 months ago
    Hello, how do you modify this code to insert *.txt files in order: 1,2,3,4,5,6,7,8,9,10,11, etc. Currently code inserts files as follows:1,10,11,12,13,14,15,16,17,18,19,2,20,21, etc. Thanks!
  • To post as a guest, your comment is unpublished.
    pooja · 10 months ago
    hi i want to prevent removing preceding zero's in excel.

    i have tried below code but it is not working


    Sub Test()
    Dim xWb As Workbook
    Dim xToBook As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xFiles As New Collection
    Dim I As Long
    Dim j As Long
    Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
    xFileDialog.AllowMultiSelect = False
    xFileDialog.Title = "Select a folder"
    If xFileDialog.Show = -1 Then
    xStrPath = xFileDialog.SelectedItems(1)
    End If
    If xStrPath = "" Then Exit Sub
    If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
    xFile = Dir(xStrPath & "*.txt")
    If xFile = "" Then
    MsgBox "No files found", vbInformation, "Kutools for Excel"
    Exit Sub
    End If
    Do While xFile <> ""
    xFiles.Add xFile, xFile
    xFile = Dir()
    Loop
    Set xToBook = ThisWorkbook
    If xFiles.Count > 0 Then
    For I = 1 To xFiles.Count
    Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
    ActiveSheet.Cells.NumberFormat = "@" 'This is to make excel in text format before pasting the text file data
    xWb.Worksheets(1).Copy After:=xToBook.Sheets(xToBook.Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = xWb.Name
    On Error GoTo 0
    xWb.Close False
    Next
    End If
    End Sub
    • To post as a guest, your comment is unpublished.
      Sunny · 10 months ago
      Pooja, you can try the Remove Leading Zeros function of Kutools for Excel to remove all leading zeros from selection after importing.
      • To post as a guest, your comment is unpublished.
        pooja · 9 months ago
        but I don't want to remove. I want to prevent from removing preceding zero's.
        • To post as a guest, your comment is unpublished.
          Sunny · 9 months ago
          If you want to keep the leading zeros, you can format them as text format by Cell Format.
  • To post as a guest, your comment is unpublished.
    Harsh · 10 months ago
    How would you delete the sheets in vba code if you dont want duplicates on re-executing the module?
    • To post as a guest, your comment is unpublished.
      Sunny · 10 months ago
      Sorry, Harsh, just be carefull to avoid repeatly importing.
  • To post as a guest, your comment is unpublished.
    John · 1 years ago
    Hi, my code runs but only imports the first file. It says there was a method error for copy. The debugger highlights the following line of code. Any ideas?


    xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
    • To post as a guest, your comment is unpublished.
      katie · 2 months ago
      I have the same problem, any solutions found?
  • To post as a guest, your comment is unpublished.
    Albeer Mayez · 1 years ago
    The Code is very helpful, it is the only code that i found which gets txt files in bulk the fix that i need on it is also what Joyce and Davinder are after.
    It is to extract the .txt files and paste them all under each other in a specific column lets say column 'N'.

    Also, need to know if it will be possible to add an "if condition" for the .txt files imported to be as follow.
    if the .txt files start with letter 'A' then to be pasted on 'sheet 1' starting with cell 'N2'
    and if the .txt files start with letter 'B' then paste on 'Sheet 2' starting with cell 'N2'
    else MsgBox to be "Unrecognised .txt file purpose".

    thank you in advance
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      Sorry, my hands are tied
    • To post as a guest, your comment is unpublished.
      Albeer Mayez · 1 years ago
      I have this code worked for me but still, I need to change some in it.

      *I want it to paste on the same sheet without opening a new sheet then copy it as it takes longer time.

      *need to insert a conditional if for txt files imported to be pasted on sheet 1 if it starts with letter A and imported to Sheet 2 if it starts with letter B


      Sub testcopy3()
      Dim xWb As Workbook
      Dim xToBook As Workbook
      Dim xStrPath As String
      Dim xFileDialog As FileDialog
      Dim xFile As String
      Dim xFiles As New Collection
      Dim i As Long
      Dim LastRow As Long
      Dim Rng As Range
      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
      If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
      xFile = Dir(xStrPath & "*.txt")
      If xFile = "" Then
      MsgBox "No files found", vbInformation, "Kutools for Excel"
      Exit Sub
      End If
      Do While xFile <> ""
      xFiles.Add xFile, xFile
      xFile = Dir()
      Loop
      Range("N2").Select
      Set xToBook = ThisWorkbook
      If xFiles.Count > 0 Then
      For i = 1 To xFiles.Count
      Set xWb = Workbooks.Open(xStrPath & xFiles.Item(i))
      xWb.Activate
      'Selecting and copying the txt data
      Range(Selection, Selection.End(xlDown)).Select
      Selection.Copy
      xToBook.Activate
      ActiveSheet.Paste
      Selection.End(xlDown).Offset(1).Select
      On Error Resume Next
      On Error GoTo 0
      xWb.Close False
      Next
      End If
      End Sub
  • To post as a guest, your comment is unpublished.
    Joyce · 1 years ago
    When I run the module as given, it adds each .txt file as a new sheet, not as a new line to the existing sheet. Is there a way to achieve that as the output instead of new sheets for each .txt file?
  • To post as a guest, your comment is unpublished.
    DF Max · 1 years ago
    how to do if my Txt file contain delimited using comma?
    • To post as a guest, your comment is unpublished.
      Sunny · 1 years ago
      You can use Find and Replace fuctuon to replace the comma with space first, and the apply one of above method to convert it to Excel file.
      • To post as a guest, your comment is unpublished.
        Robin · 1 years ago
        Isn't there a way to change this in the code? I'd have to do this with 130 files
  • To post as a guest, your comment is unpublished.
    P B Rama Murty · 2 years ago
    Sub Test()
    'UpdatebyExtendoffice6/7/2016
    Dim xWb As Workbook
    Dim xToBook As Workbook
    Dim xStrPath As String
    Dim xFileDialog As FileDialog
    Dim xFile As String
    Dim xFiles As New Collection
    Dim I As Long
    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
    If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
    xFile = Dir(xStrPath & "*.txt")
    If xFile = "" Then
    MsgBox "No files found", vbInformation, "Kutools for Excel"
    Exit Sub
    End If
    Do While xFile <> ""
    xFiles.Add xFile, xFile
    xFile = Dir()
    Loop
    Set xToBook = ThisWorkbook
    If xFiles.Count > 0 Then
    For I = 1 To xFiles.Count
    Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
    xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = xWb.Name
    On Error GoTo 0
    xWb.Close False
    Next
    End If
    End Sub

    this code is helping but I want

    tab, semi colon, space true how to do this please help me
    • To post as a guest, your comment is unpublished.
      Sunny · 2 years ago
      Do you want to keep the space(delimiters) after converting the text files to sheets?
      • To post as a guest, your comment is unpublished.
        farzaneh · 2 years ago
        that is my problem too, this code is true. but after convert text files to excel, it doesn't keep the delimiters.
        • To post as a guest, your comment is unpublished.
          Sunny · 2 years ago
          Could you upload the text file and the result you want for me?
          • To post as a guest, your comment is unpublished.
            Des · 1 years ago
            I have the same problem. The txt files are all in separate sheets and the code ignores the space between the two columns
            • To post as a guest, your comment is unpublished.
              Sunny · 1 years ago
              Hello, Des and P B Rama Murty, the below code can split data into columns based on space or tab while importing text file to sheets. You can have a try.

              Sub ImportTextToExcel()
              'UpdatebyExtendoffice20180911
              Dim xWb As Workbook
              Dim xToBook As Workbook
              Dim xStrPath As String
              Dim xFileDialog As FileDialog
              Dim xFile As String
              Dim xFiles As New Collection
              Dim I As Long
              Dim xIntRow As Long
              Dim xFNum, xFArr As Long
              Dim xStrValue As String
              Dim xRg As Range
              Dim xArr
              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
              If Right(xStrPath, 1) <> "\" Then xStrPath = xStrPath & "\"
              xFile = Dir(xStrPath & "*.txt")
              If xFile = "" Then
              MsgBox "No files found", vbInformation, "Kutools for Excel"
              Exit Sub
              End If
              Do While xFile <> ""
              xFiles.Add xFile, xFile
              xFile = Dir()
              Loop
              Set xToBook = ThisWorkbook
              On Error Resume Next
              Application.ScreenUpdating = False
              If xFiles.Count > 0 Then

              For I = 1 To xFiles.Count
              Set xWb = Workbooks.Open(xStrPath & xFiles.Item(I))
              xWb.Worksheets(1).Copy after:=xToBook.Sheets(xToBook.Sheets.Count)

              ActiveSheet.Name = xWb.Name

              xWb.Close False
              xIntRow = ActiveCell.CurrentRegion.Rows.Count
              For xFNum = 1 To xIntRow
              Set xRg = ActiveSheet.Range("A" & xFNum)
              xArr = Split(xRg.Text, " ")
              If UBound(xArr) > 0 Then
              For xFArr = 0 To UBound(xArr)
              If xArr(xFArr) <> "" Then
              xRg.Value = xArr(xFArr)
              Set xRg = xRg.Offset(ColumnOffset:=1)
              End If
              Next
              End If
              Next
              Next
              End If
              Application.ScreenUpdating = True
              End Sub