0

I want to concatenate several text files structured in the exact same way, but I want to keep the first line only for the first file and kill that header line for the consecutive 20+ files. Thus far, I've been able to concatenate by using the following script, but I don't know how to avoid the first line.

Sub snb() 'This Macro opens all .txt files in a given path and concatenates them
    c00 = "C:\some path" ' the path
    c01 = Dir(c00 & "*.txt")
    Location = "destination_path\" 'Here is where the combined file will be

    DateStamp = CStr(Year(Date)) & CStr(Month(Date)) & CStr(Day(Date))


    x = 0

    Do Until c01 = ""

        If x = 0 Then

            c02 = c02 & CreateObject("scripting.filesystemobject").opentextfile(c00 & c01).readall
            c01 = Dir
            x = 1

        Else

            c02 = c02 & vbCrLf & CreateObject("scripting.filesystemobject").opentextfile(c00 & c01).readall '
            c01 = Dir

        End If
    Loop

    CreateObject("scripting.filesystemobject").createtextfile(Location & DateStamp & "_new.txt").write c02

End Sub
Community
  • 1
  • 1
  • Is this `VBA` or `vb.net`? – Bjørn-Roger Kringsjå Jan 13 '14 at 18:18
  • Take a look at [this question](http://stackoverflow.com/questions/11528694/read-parse-text-file-line-by-line-in-vba). You may be able to use an IF statement and a count variable to determine if you have already used line 1. – thunderblaster Jan 13 '14 at 18:32
  • Don't concatenate subsequent files immediately. Read them into a temporary string. Search that string for vbCrLf (end of first line) and then concatenate the remainder of the string. – Tony Dallimore Jan 13 '14 at 18:36

1 Answers1

0

Here's what your If statement should look like :

If x = 0 Then

    c02 = c02 & CreateObject("scripting.filesystemobject").opentextfile(c00 & c01).readall
    c01 = Dir
    x = 1

Else

    fs = CreateObject("Scripting.filesystemobject").opentextfile(c00 & c01).readall
    toRemove = InStr(fs, vbCrLf) + 1
    fs = Right(CStr(fs), Len(fs) - toRemove)
    c02 = c02 & vbCrLf & fs
    c01 = Dir

End If

What this does is :

  1. Extracts entire file content
  2. Finds the first "Line Feed" character
  3. Creates a string with everything following that "Line Feed"
  4. Concatenates that string into the cumulative c02.
Bernard Saucier
  • 2,240
  • 1
  • 19
  • 28