web 2.0


How to append text files using VBA

If you are working with text files and need to merge or append data; here’s a good way to carry that out using VBA.

In this simple example, you should have two text files placed in the same location where the Excel workbook is located (notice how the file is opened in the code). In file number 2 (I called it “File2.txt”) you should write something (one or two lines of text for testing purposes). File number 1 you can leave blank, as data from file 2 will be appended to it. 

You are now ready. Copy the VBA code below and paste it into your workbook. You can now run it: 

Sub AppendTextFiles()

'   The file that contains the data to be copied over
    Open ThisWorkbook.Path & "\File2.txt" For Input As #2


'   The file where the data will be appended
    Open ThisWorkbook.Path & "\File1.txt" For Append As #1


'   Loop through the data in file number 2 (#2) ...
    Do Until EOF(2)
        Line Input #2, Data


'       ... and append (write) the data into file number 1 (#1)
        Write #1, Data
    Loop


'   Close the files
    Close #2
    Close #1
End Sub
 
  

 

Tags: ,

Microsoft Office | Microsoft Office - VBA

Comments

Comments are closed