Import Text Files onto SAME worksheet

L

Legacy 323112

Guest
Hi all,
I'm looking to navigate to a folder, select txt files, and import each onto the same worksheet in an existing workbook, one after another (vertically). I found some code on;
Importing Multiple Files to a Single Workbook (Microsoft Excel)
which almost does exactly what I need, although it creates a new workbook and it imports each .txt file onto a new worksheet.

Does anybody know how to tweak it such that each .txt file can be imported sequentially onto the same worksheet of my existing workbook?

Any advice would be most appreciated!

Code:
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
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.
the following may not be complete yet but is probably on the right lines
Code:
Option Explicit

Sub CombineTextFiles()
    Dim FilesToOpen
    Dim x As Integer
    Dim wkbTemp As Workbook
    Const sDelimiter As String = "|"
    
    Dim wsMyWorksheet As Worksheet: Set wsMyWorksheet = Sheet1
    
    On Error GoTo ErrHandler
    Application.ScreenUpdating = False

    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

    While x <= UBound(FilesToOpen)
        
        Set wkbTemp = Workbooks.Open(Filename:=FilesToOpen(x))
        
        wkbTemp.Sheets(1).UsedRange.Copy
        wsMyWorksheet.Cells(lastUsedRow(wsMyWorksheet) + 3, 1).Paste
        
        wkbTemp.Close (False)
        
        x = x + 1
    Wend

    wsMyWorksheet.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

ExitHandler:
    Application.ScreenUpdating = True
    Set wkbTemp = Nothing
    Exit Sub

ErrHandler:
    MsgBox Err.Description
    Resume ExitHandler
End Sub

Function lastUsedRow(ws As Worksheet) As Long

On Error Resume Next
    lastUsedRow = ws.Cells.Find("*", Range("A1"), xlFormulas, , xlByRows, xlPrevious).Row
On Error GoTo 0

End Function
 
Upvote 0
Solution
Thanks so much for your quick response!
I've tried the code but keep getting 'subscript out of range'
Where can I change the name of the worksheet?

Thanks
 
Upvote 0
Actually, I'm not sure its to do with the sheet name, as I have tried renaming my worksheets
 
Upvote 0
Sorry should have highlighted it. I created a worksheet object that needs to refer to the worksheet that you want to paste the data to. For now I put
Code:
Dim wsMyWorksheet As Worksheet: Set wsMyWorksheet = Sheet1
but you may need to reconfigure this. What's the name (Excel) and codename (VBA) for your worksheet?
 
Upvote 0
Actually, I'm not sure its to do with the sheet name, as I have tried renaming my worksheets
I'm using the codename, which is how VBA sees it. This is usually better than using the Excel tab name, which can be changed by the user. Take a look in the VB Editor, project explorer, and you'll see 2 names for each worksheet. One is the VBA version, the other is the Excel version, the VBA codename ignores the Excel name
 
Upvote 0
Thanks, so Sheet1 refers to the first sheet in the workbook regardless of its name?
In which case, not sure why I'm getting the error..
It's an empty sheet
 
Upvote 0
Hi,
Thanks so much, this works now! Only one thing, if you see the screenshot below, you'll notice that data in columns B & C are not aligned with that in column A. This does not happen if I was to copy the text in directly to the spreadsheet. Any ideas?
 
Last edited by a moderator:
Upvote 0
Example;



Field 1
Yes
YesField 2Field 3
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYesYes
YesYes
YesYes
Field 1
Yes
YesField 2Field 3
YesYesYes
YesYesYes
YesYesYes

<colgroup><col style="width:48pt" span="3" width="64"> </colgroup><tbody>
</tbody>
 
Last edited by a moderator:
Upvote 0

Forum statistics

Threads
1,214,986
Messages
6,122,611
Members
449,090
Latest member
vivek chauhan

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