MrExcel Publishing
Your One Stop for Excel Tips & Solutions

Who can merge txt files

Posted by help_me on October 31, 2001 3:51 AM

hello all,

new to the VB game and was wondering could someone spare me some code that
takes two input files input1.txt and input2.txt
deletes the first 12 lines of input2.txt
adds input2.txt onto the end of input1.txt
saves as input1.txt

thanks for any help,

Posted by Bob Umlas on October 31, 2001 4:07 AM

This is ripe for simply recording the steps. The playback will be pretty straightforward, and the learning will be most instructive.

Posted by conor on October 31, 2001 4:35 AM

already tried but the size of the two txt files change and by recording i am restricting to appending to a particular range of fields - ie i "paste" to cells Ax:Dx

i need it generic so it appends always to the end no matter what size

ta, any sugestions????

Posted by Barrie Davidson on October 31, 2001 6:15 AM

Conor, can you post your recorded macro (then I can change it so it is dynamic)?

BarrieBarrie Davidson

Posted by Damon Ostrander on October 31, 2001 11:35 AM

Hi Conor,

Here is a simple macro that does what you describe. The two files must be in the Excel working (default) directory. If you are not currently in the working directory, you can set it by doing an Excel File -> Open, browse to the directory, then Cancel out of the open.

There is no length restriction on the file sizes with this macro.

Happy merging.


Sub MergeFiles()

' This routine concatenates two files, input1.txt and input2.txt, into
' input1.txt that contains the original input1.txt followed by all but the
' first 12 records of the input2.txt file

Dim InRec As String
Dim iRec As Long

Open "Input1.txt" For Append As #1
Open "Input2.txt" For Input As #2

' copy Text2.txt, skipping 1st 12 records
For iRec = 1 To 12
Line Input #2, InRec
If EOF(2) Then GoTo Done
Next iRec
'write remainder of records
Line Input #2, InRec
Print #1, InRec
Loop Until EOF(2)

Close 'all files
MsgBox "Merge complete, Input2.txt appended to Input1.txt", _
vbInformation, _
"Merge Status"

End Sub