Append Text from One Text File to Another
The following macro appends text from one text file to another using the file input and output commands. Note that if the specified destination file doesn't exist, one will be created.
'Force the explicit
declaration of variables
Option Explicit
Sub
AppendFile()
'Declare the variables
Dim sSourceFile As String
Dim sDestFile As String
Dim sLineOfText As String
Dim
SourceFileNum As
Long
Dim DestFileNum As Long
'If an error occurs, go to
ErrHandler
On Error GoTo ErrHandler
'Assign the path and name of
the source file to a variable
sSourceFile =
"C:\Users\Domenic\Documents\TextFile1.txt"
'Assign the path and name of
the destination file to a variable
sDestFile = "C:\Users\Domenic\Documents\TextFile2.txt"
'Open the source file
SourceFileNum = FreeFile()
Open sSourceFile
For Input As SourceFileNum
'Open the destination file
DestFileNum = FreeFile()
Open sDestFile For Append As DestFileNum
'Include the following line
if the first line of the source
'file is a header row and you
don't want to append it to
'the destination file:
'Line Input #SourceFileNum,
sLineOfText
'Read each line of the source
file and append it to the destination file
Do Until
EOF(SourceFileNum)
Line
Input
#SourceFileNum, sLineOfText
Print
#DestFileNum, sLineOfText
Loop
'Close the source file and
destination file
Close
#SourceFileNum
Close
#DestFileNum
MsgBox "Completed...",
vbInformation
Exit Sub
ErrHandler:
MsgBox
"Error " & Err.Number & ": " & Err.Description
End Sub
Where to Put the Code
- Open the workbook in which to store the code.
- Open the Visual Basic Editor (Alt+F11).
- Insert a standard module (Insert > Module).
- Copy/paste the above code into the module.
- Return to Microsoft Excel (Alt+Q).
- Save the workbook.
How to Use the Macro
- Display the Macro dialog box (Alt+F8).
- Click/select the macro called "AppendFile".
- Click/select "Run".
Sample Workbook: Download