Excel.Tips.Net: Importing Multiple Files to a Single Workbook

By Allen Wyatt for Excel.Tips.Net

Importing Multiple Files to a Single Workbook

Let’s say that you have a folder on your hard drive that contains thirty text files, and you want to import all of them to an Excel workbook. You want each text file to end up on its own worksheet in the workbook, so that you will have a total of thirty worksheets.

One way to do this is to manually add the desired worksheets, and then individually import each of the text files. This, as you can imagine, would quickly get tedious. A much better solution is to use a macro to do the importing, such as the following one.

Sub CombineTextFiles()
Dim FilesToOpen
Dim x As Integer
Dim wkbAll As Workbook
Dim wkbTemp As Workbook
Dim sDelimiter As String

On Error GoTo ErrHandler
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”
GoTo ExitHandler
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:=False, _
Tab:=False, Semicolon:=False, _
Comma:=False, Space:=False, _
Other:=True, 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:=False, _ Tab:=False, Semicolon:=False, _ Comma:=False, Space:=False, _ Other:=True, OtherChar:=sDelimiter End With x = x + 1 Wend ExitHandler: Application.ScreenUpdating = True Set wkbAll = Nothing Set wkbTemp = Nothing Exit Sub ErrHandler: MsgBox Err.Description Resume ExitHandler End Sub


Article Continued Here

Stop Responding to Threats.
Prevent Them.

Want to get monthly tips & tricks?

Subscribe to our newsletter to get cybersecurity tips & tricks and stay up to date with the constantly evolving world of cybersecurity.

Related Articles