Search code examples
excelvbacopy-pastetxt

How to copy the whole txt file to Excel


I have a code which doesn't completely work:

Sub Import_TXT()
    Dim FileToOpen As Variant
    Dim OpenBook As Workbook

    Application.GetOpenFilename ("Text Files (*.txt), *.txt")
    If FileToOpen <> False Then
        Set OpenBook = Application.Workbooks.Open(FileToOpen)
        OpenBook.Sheets(1).Range("A1").Copy
        ThisWorkbook.Worksheets("BOM").Range("C1").PasteSpecial xlPasteValues
        OpenBook.colse False
    End If
End Sub

I am trying to paste all contents of a txt file to cell "C1" of the active workbook sheet "BOM"

By fixing code as suggested I got:

Sub Import_TXT()

Dim FileToOpen As Variant
Dim OpenBook As Workbook

FileToOpen = Application.GetOpenFilename("Text Files (*.txt), *.txt")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Cells.Copy
ThisWorkbook.Worksheets("BOM").Range("A1").PasteSpecial xlPasteValues
OpenBook.Close False
End If

End Sub

Which now pastes all the contents in cell "A1" when I need it in "C1". There's an error popping out when I change

ThisWorkbook.Worksheets("BOM").Range("A1").PasteSpecial xlPasteValues

to

ThisWorkbook.Worksheets("BOM").Range("C1").PasteSpecial xlPasteValues

Saying that I only can paste in "A1"

By simply changing

.cells

To

.UsedRange

I can define cell "C1" as range where to paste all the contents


Solution

  • This code will loop through all text files in a folder, and import one file into one cell, then import another files into another cell, and so on and so forth.

    Sub Import_All_Text_Files()
    
        Application.ScreenUpdating = False
    
        Dim thisRow As Long
        Dim fileNum As Integer
        Dim strInput As String
    
        Const strPath As String = "C:\your_path_here\"  'Change as required
        Dim strFilename As String
    
        strFilename = Dir(strPath & "*.txt")
    
        With ActiveSheet
            thisRow = .Range("A" & .Rows.Count).End(xlUp).Row
    
            Do While strFilename <> ""
    
                fileNum = FreeFile()
                Open strPath & strFilename For Binary As #fileNum
                strInput = Space$(LOF(fileNum))
                Get #fileNum, , strInput
                Close #fileNum
    
                thisRow = thisRow + 1
                .Cells(thisRow, 1).Value = strInput
    
                strFilename = Dir
            Loop
        End With
    
        Application.ScreenUpdating = True
    
    End Sub
    

    If you have just one file that you need to import, it will import only that one.