Import multiple text files to separated sheets onto current workbook

llbac

New Member
Joined
Jul 20, 2023
Messages
30
Office Version
  1. 365
Platform
  1. Windows
Hi everyone!

I got a VBA code that can work successfully to import multiple text files to separated sheets.
However, it creates a new workbook, say Book1, while I expect to load all new imported sheets to the current workbook which I am running this VBA code.
So, I hope someone could take a look on the codes and change where it is needed to meet this requirement.
Thank you very much!

VBA Code:
Sub Import_Text_Files()
Dim FilesToOpen
    Dim x As Integer
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim sDelimiter As String
    Application.ScreenUpdating = False
    sDelimiter = "|"

    FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.txt), *.txt", _
      MultiSelect:=True, Title:="Text Files to Open")
    If TypeName(FilesToOpen) = "Boolean" Then
        MsgBox "No Files were selected"
    End If
    x = 1
    Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
    wkbTemp.Sheets(1).Copy
    Set wkbAll = ActiveWorkbook
    wkbTemp.Close (False)
    wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=True, _
      Tab:=False, Semicolon:=False, _
      Comma:=True, Space:=True, _
      Other:=False, OtherChar:="|"
     
   x = x + 1

    While x <= UBound(FilesToOpen)
        Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
        With wkbAll
            wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
            .Worksheets(x).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              ConsecutiveDelimiter:=True, _
              Tab:=False, Semicolon:=False, _
              Comma:=True, Space:=True, _
              Other:=False, OtherChar:=sDelimiter
                
        End With

        x = x + 1
    Wend
    Application.ScreenUpdating = True
End Sub
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney
Hi everyone!

I got a VBA code that can work successfully to import multiple text files to separated sheets.
However, it creates a new workbook, say Book1, while I expect to load all new imported sheets to the current workbook which I am running this VBA code.
So, I hope someone could take a look on the codes and change where it is needed to meet this requirement.
Thank you very much!

VBA Code:
Sub Import_Text_Files()
Dim FilesToOpen
    Dim x As Integer
    Dim wkbAll As Workbook
    Dim wkbTemp As Workbook
    Dim sDelimiter As String
    Application.ScreenUpdating = False
    sDelimiter = "|"

    FilesToOpen = Application.GetOpenFilename _
      (FileFilter:="Text Files (*.txt), *.txt", _
      MultiSelect:=True, Title:="Text Files to Open")
    If TypeName(FilesToOpen) = "Boolean" Then
        MsgBox "No Files were selected"
    End If
    x = 1
    Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
    wkbTemp.Sheets(1).Copy
    Set wkbAll = ActiveWorkbook
    wkbTemp.Close (False)
    wkbAll.Worksheets(x).Columns("A:A").TextToColumns _
      Destination:=Range("A1"), DataType:=xlDelimited, _
      TextQualifier:=xlDoubleQuote, _
      ConsecutiveDelimiter:=True, _
      Tab:=False, Semicolon:=False, _
      Comma:=True, Space:=True, _
      Other:=False, OtherChar:="|"
    
   x = x + 1

    While x <= UBound(FilesToOpen)
        Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
        With wkbAll
            wkbTemp.Sheets(1).Move After:=.Sheets(.Sheets.Count)
            .Worksheets(x).Columns("A:A").TextToColumns _
              Destination:=Range("A1"), DataType:=xlDelimited, _
              TextQualifier:=xlDoubleQuote, _
              ConsecutiveDelimiter:=True, _
              Tab:=False, Semicolon:=False, _
              Comma:=True, Space:=True, _
              Other:=False, OtherChar:=sDelimiter
               
        End With

        x = x + 1
    Wend
    Application.ScreenUpdating = True
End Sub
It is this line that creates a new workbook:

wkbTemp.Sheets(1).Copy

What format are the text files in?

Can you post using XL2BB a sample of the data?
 
Upvote 0
It is this line that creates a new workbook:



What format are the text files in?

Can you post using XL2BB a sample of the data?

I am not quite sure that I understand your question correctly.
After importing, the data will be mostly number or text.
Is that related with the importing process?

As I mentioned, this code worked well, the problem is that it creates a new workbook.
I created myself an excel template with a sheet named "Master", then I assigned this macro to a button in "Master" sheet.
I expect that after clicking the button it will import all text files to separated sheets onto my current workbook after the sheet "Master".

Hope to hear from you!
 
Upvote 0
Here is a macro that will import multiple CSV files into you open and active Workbook.
Sheet names will be the file name (without path information).
You might be able to remove some of the parameter settings assuming the default values will work for your source files.
The macro was created by recording the import of a comma delimited file via the Data->From Text (and following dialog responses)

I hope you can use this.

VBA Code:
Sub Macro1()
'
' Macro1 Macro
'
  Dim FilesToOpen
  Dim x, tmp
'
  FilesToOpen = Application.GetOpenFilename _
    (FileFilter:="Text Files (*.txt), *.txt", _
    MultiSelect:=True, Title:="Text Files to Open")
  If TypeName(FilesToOpen) = "Boolean" Then
      MsgBox "No Files were selected"
      Exit Sub
  End If
    
  For Each x In FilesToOpen
    ActiveWorkbook.Worksheets.Add After:=Sheets(Sheets.Count)
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & x, Destination:=Range("$A$1"))
'        .CommandType = 0
        tmp = Mid(x, InStrRev(x, "\") + 1)
        .Name = Mid(tmp, 1, Len(tmp) - 4)
        .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 = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
  Next
  ActiveWindow.SmallScroll Down:=0
End Sub
 
Upvote 0
Here is a macro that will import multiple CSV files into you open and active Workbook.
Sheet names will be the file name (without path information).
You might be able to remove some of the parameter settings assuming the default values will work for your source files.
The macro was created by recording the import of a comma delimited file via the Data->From Text (and following dialog responses)

I hope you can use this.

VBA Code:
Sub Macro1()
'
' Macro1 Macro
'
  Dim FilesToOpen
  Dim x, tmp
'
  FilesToOpen = Application.GetOpenFilename _
    (FileFilter:="Text Files (*.txt), *.txt", _
    MultiSelect:=True, Title:="Text Files to Open")
  If TypeName(FilesToOpen) = "Boolean" Then
      MsgBox "No Files were selected"
      Exit Sub
  End If
   
  For Each x In FilesToOpen
    ActiveWorkbook.Worksheets.Add After:=Sheets(Sheets.Count)
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & x, Destination:=Range("$A$1"))
'        .CommandType = 0
        tmp = Mid(x, InStrRev(x, "\") + 1)
        .Name = Mid(tmp, 1, Len(tmp) - 4)
        .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 = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
  Next
  ActiveWindow.SmallScroll Down:=0
End Sub
Dear @Bosquedeguate , your code works like a charm!
However, could you do me a favor that keeps the original file names after importing?
Currently, all the new sheet has been named as Sheet1, Sheet2, Sheet3 etc.
I would like to retain the original file names to track what are imported.
Thank you very much!
 
Upvote 0
I added code to rename the new sheet to the file name of the imported file (without file extension). Will that work for you?

VBA Code:
Sub Macro1()
'
' Macro1 Macro
'
  Dim FilesToOpen
  Dim x, tmp
'
  FilesToOpen = Application.GetOpenFilename _
    (FileFilter:="Text Files (*.txt), *.txt", _
    MultiSelect:=True, Title:="Text Files to Open")
  If TypeName(FilesToOpen) = "Boolean" Then
      MsgBox "No Files were selected"
      Exit Sub
  End If
   
  For Each x In FilesToOpen
    ActiveWorkbook.Worksheets.Add After:=Sheets(Sheets.Count)
    tmp = Mid(x, InStrRev(x, "\") + 1)
    ActiveSheet.Name = Mid(tmp, 1, Len(tmp) - 4)
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & x, Destination:=Range("$A$1"))
'        .CommandType = 0
        .Name = Mid(tmp, 1, Len(tmp) - 4)
        .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 = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
  Next
  ActiveWindow.SmallScroll Down:=0
End Sub
 
Upvote 0
Solution
I added code to rename the new sheet to the file name of the imported file (without file extension). Will that work for you?

VBA Code:
Sub Macro1()
'
' Macro1 Macro
'
  Dim FilesToOpen
  Dim x, tmp
'
  FilesToOpen = Application.GetOpenFilename _
    (FileFilter:="Text Files (*.txt), *.txt", _
    MultiSelect:=True, Title:="Text Files to Open")
  If TypeName(FilesToOpen) = "Boolean" Then
      MsgBox "No Files were selected"
      Exit Sub
  End If
  
  For Each x In FilesToOpen
    ActiveWorkbook.Worksheets.Add After:=Sheets(Sheets.Count)
    tmp = Mid(x, InStrRev(x, "\") + 1)
    ActiveSheet.Name = Mid(tmp, 1, Len(tmp) - 4)
    With ActiveSheet.QueryTables.Add(Connection:="TEXT;" & x, Destination:=Range("$A$1"))
'        .CommandType = 0
        .Name = Mid(tmp, 1, Len(tmp) - 4)
        .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 = True
        .TextFileTabDelimiter = False
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = True
        .TextFileColumnDataTypes = Array(1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
  Next
  ActiveWindow.SmallScroll Down:=0
End Sub
It worked perfectly now!
Thank you so much!
 
Upvote 0

Forum statistics

Threads
1,215,071
Messages
6,122,963
Members
449,094
Latest member
Anshu121

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top