concatenate 2 text files inside VBA

J

Jim

I have 2 tables that have different structures. My final result should
be one text file containing fixed field lengths in one table. Both
output files have a fixed record length of 350 characters.

I now export both tables but need to concatenate them into one file. A
DOS COPY will do the trick. I tried FILECOPY but it only takes one file .

Any suggestions

Jim
 
J

Jim

I found a solution. read the text from the source files and put that in
a third:

You can read from (or write to) a text file using the Open statement,
Close statement and various other statements for actually reading/writing.

The Open statement has clauses for what type of access you want to the
file, so you can specify if you want to read it as text, write to it as
binary, and so on. You can also set locking options, to stop other
programs from opening the file. For more details, go to the Index of VB
help and see "Open statement".

For all of these file access functions you need to specify a file
number, which most people use 1 for. You should always use a number
which is not already in use (as using the same will cause an error),
luckily the next free number can be found using the FreeFile function as
in the example below.

Option Explicit

Private Sub Command0_Click()
'FileCopy "c:\a.txt" & "c:\b.txt", "C.txt"

'Set a reference to "Microsoft Scripting Runtime"

'declare and initiate required objects
Dim fs As FileSystemObject
Dim ts_in As TextStream
Dim ts_out As TextStream
Dim recordBucket As String
Dim theFile As String
Dim x As Double

Set fs = New FileSystemObject
Set ts_out = fs.OpenTextFile("C:\c.txt", ForWriting, True)

'To write
'Set ts_in = fs.OpenTextFile("C:\a.txt", ForWriting, True)
'ts_in.WriteLine "I Love"
'ts_in.WriteLine "VB Forums"
'ts_in.Close

'To Read and write
For x = 1 To 2
If x = 1 Then
theFile = "C:\a.txt"
Else
theFile = "C:\b.txt"
End If

If fs.FileExists(theFile) Then
Set ts_in = fs.OpenTextFile(theFile)
' Set ts_out = fs.OpenTextFile("C:\c.txt", ForWriting, True)

Do While Not ts_in.AtEndOfStream
' MsgBox ts_in.ReadLine
recordBucket = ts_in.ReadLine
ts_out.WriteLine recordBucket
Loop
ts_in.Close
End If

Next x

'clear memory used by FSO objects
Set ts_in = Nothing
Set ts_out = Nothing
Set fs = Nothing

End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top