• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

Merge CSV files - little bug

rolo

Member
Hello, I am using this great macro to merge 2 csv files into 1 csv file
(credits: http://analystcave.com/merge-csv-files-or-txt-files-in-a-folder/)

The problem is that the combined file has 20 rows, but row 11 stays empty!

Any suggestion on how to fix it?
I provide the vba code and 2 csv example files to combine

Thanks


Code:
Sub MergeMyCSVFiles()

'MergeFiles Parameters
'
'fileNames()
'Array of Strings representing full file paths to files that are to be merged
'
'newFileName
'The name of the new merged file that is to be created
'
'headers
'Optional. True by default. This is meant for CSV TXT files (HDR). If True assumes that all files have headers (first row with columns). Only first header will be merged into the new file (newFileName)
'
'addNewLine
'Optional. False by default. If True a new line (vbNewLine) character will be added between each merged file

Dim fileNames(0 To 1) As String
fileNames(0) = "D:\Temp\Cel\TestData1.csv"
fileNames(1) = "D:\Temp\Cel\TestData2.csv"
   
MergeFiles fileNames, "D:\Temp\Cel\Final\TestData3.csv", True, False
End Sub


Sub MergeFiles(fileNames() As String, newFileName As String, Optional headers As Boolean = True, Optional addNewLine As Boolean = False)
    Dim fileName As Variant, textData As String, fileNo As Integer, result As String, firstHeader As Boolean
    firstHeader = True
    For Each fileName In fileNames
        fileNo = FreeFile
        Open fileName For Input As #fileNo
        textData = Input$(LOF(fileNo), fileNo)
        Close #fileNo
        If headers Then
            result = result & IIf(addNewLine, vbNewLine, "") & IIf(firstHeader, textData, Right(textData, Len(textData) - InStr(textData, vbNewLine)))
            firstHeader = False
        Else
            result = result & IIf(addNewLine, vbNewLine, "") & textData
        End If
    Next fileName
    fileNo = FreeFile
    Open newFileName For Output As #fileNo
    Print #fileNo, result
    Close #fileNo
End Sub
 

Attachments

Hi ,

Change the following line of code as shown here :

result = result & IIf(addNewLine, vbNewLine, "") & IIf(firstHeader, textData, Right(textData, Len(textData) - InStr(textData, vbNewLine) - 1))

Narayan
 
Back
Top