CodeItBetter Programming Another VB Programming Blog

How to merge two text files

Posted on January 4, 2009
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
'Text File Handling - How to merge two text files
Public Function MergeTwoTextFiles(ByVal strTextFile1 As String, ByVal strTextFile2 As String)
'This function is used to merge two text files.
'Call this function as:
'Call MergeTwoTextFiles("C:\Temp\a.txt", "C:\Temp\a1.txt")
'
    Dim strText As String
    Open strTextFile2 For Input As #1
    strText = Input$(LOF(1), #1)
    Close #1
    'Add the content of text file 2 to text file 1
    Call WriteTextFileContents(strText, strTextFile1, True)
End Function
 
Sub WriteTextFileContents(Text As String, filename As String, Optional AppendMode As Boolean)
    Dim fnum As Integer, isOpen As Boolean
    On Error GoTo Error_Handler
    ' Get the next free file number.
    fnum = FreeFile()
    If AppendMode Then
        Open filename For Append As #fnum
    Else
        Open filename For Output As #fnum
    End If
    ' If execution flow gets here, the file has been opened correctly.
    isOpen = True
    ' Print to the file in one single operation.
    Print #fnum, Text
    ' Intentionally flow into the error handler to close the file.
Error_Handler:
    ' Raise the error (if any), but first close the file.
    If isOpen Then Close #fnum
    If Err Then Err.Raise Err.Number, , Err.Description
End Sub
Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


 

No trackbacks yet.