How to merge/join/append/concatenate files in VB6 with FileSystemObject
Private Sub Command1_Click()
Dim folder As String
Dim dest_file As String
Dim file_ext As String
Dim lPid As Long
Dim shellStr As String
Dim rvShellStr As String
rvShellStr = ""
folder = "C:\myFolder\mySubFolder\"
dest_file = "MergeFileName"
file_ext = "*.txt"
Dim srcFolder As String
srcFolder = folder + file_ext
Dim destFile As String
destFile = folder + dest_file + ".txt"
'------------------------------------------
'kill target file
'------------------------------------------
On Error Resume Next
Kill destFile
'------------------------------------------
'get file list from source file
'------------------------------------------
Dim fileArray() As String
fileArray = Me.FileList(srcFolder)
'------------------------------------------
'ConcatenateFiles
'------------------------------------------
Call ConcatenateFiles(folder, destFile, fileArray)
'------------------------------------------
'all done
'------------------------------------------
MsgBox ("All Done")
End Sub
Public Function FileList(Mask As String) As String()
Dim sWkg As String
Dim sAns() As String
Dim lCtr As Long
ReDim sAns(0) As String
sWkg = Dir(Mask, vbNormal)
Do While Len(sWkg)
If sAns(0) = "" Then
sAns(0) = sWkg
Else
lCtr = UBound(sAns) + 1
ReDim Preserve sAns(lCtr) As String
sAns(lCtr) = sWkg
End If
sWkg = Dir
Loop
FileList = sAns
End Function
Private Sub ConcatenateFiles(ByVal folder As String, ByVal ResultFile As String, _
SourceFiles() As String)
' Concatenate a variable number of text files into a single result file
'
' Params:
' - ResultFile: the complete path of the result file you want to create
' - Separator: a string that is written when a file is added to the result
' file.
' Note: this string can contain the #FilePath# tag that will be replaced
' with the path of the file being added
' - SourceFiles: a sequence of files whose content will be concatenated
'
' Example:
' ConcatenateFiles "D:\res.txt", "------ NEW FILE: #FilePath# ------",
' "D:\1.txt", "D:\2.txt", "D:\3.txt"
Dim Separator As String
Separator = vbCrLf
Dim FSO As New Scripting.FileSystemObject
Dim fsSourceStream As TextStream
Dim fsResStream As TextStream
Dim sSeparator As String
Dim i As Integer
On Error Resume Next
' create a new file
Set fsResStream = FSO.OpenTextFile(ResultFile, ForWriting, True)
' for each source file in the input array
For i = 0 To UBound(SourceFiles)
' add the separator first (replacing the special tag for the file path)
Dim sourceFileName As String
sourceFileName = folder + SourceFiles(i)
' sSeparator = Replace(Separator, "#FilePath#", SourceFiles(i))
' fsResStream.Write sSeparator & vbCrLf
' ' open the file in read mode
Set fsSourceStream = FSO.OpenTextFile(sourceFileName, ForReading)
' add its content + a blank line to the result file
fsResStream.Write fsSourceStream.ReadAll ' & vbCrLf
' close this source file
fsSourceStream.Close
Next i
fsResStream.Close
End Sub