简体   繁体   中英

VBA convert multiple Excel files to CSV and remove trailing commas

I have a large number of xlsx reports that I need to convert to csv for import into another program. However, when Excel converts them it adds trailing commas that prevent the file from being read by the software.

I found this script online to convert an entire folder of files to csv and it has worked well for me.

    Sub WorkbooksPrepAndSaveAsCsvToFolder()
'UpdatebyExtendoffice20181031
Dim xObjWB As Workbook
Dim xObjWS As Worksheet
Dim xStrEFPath As String
Dim xStrEFFile As String
Dim xObjFD As FileDialog
Dim xObjSFD As FileDialog
Dim xStrSPath As String
Dim xStrCSVFName As String


    Application.ScreenUpdating = False
    Application.EnableEvents = False
    Application.Calculation = xlCalculationManual
    On Error Resume Next
Set xObjFD = Application.FileDialog(msoFileDialogFolderPicker)
    xObjFD.AllowMultiSelect = False
    xObjFD.Title = "Kutools for Excel - Select a folder which contains Excel files"
    If xObjFD.Show <> -1 Then Exit Sub
    xStrEFPath = xObjFD.SelectedItems(1) & "\"

    Set xObjSFD = Application.FileDialog(msoFileDialogFolderPicker)

    xObjSFD.AllowMultiSelect = False
    xObjSFD.Title = "Kutools for Excel - Select a folder to locate CSV files"
    If xObjSFD.Show <> -1 Then Exit Sub
    xStrSPath = xObjSFD.SelectedItems(1) & "\"

    xStrEFFile = Dir(xStrEFPath & "*.xls*")

    Do While xStrEFFile <> ""
        Set xObjWB = Workbooks.Open(Filename:=xStrEFPath & xStrEFFile)
        xStrCSVFName = xStrSPath & Left(xStrEFFile, InStr(1, xStrEFFile, ".xlsx") - 1) & ".csv"
        xObjWB.SaveAs Filename:=xStrCSVFName, FileFormat:=xlCSV
        xObjWB.Close savechanges:=False
        xStrEFFile = Dir
  Loop
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True
    Application.ScreenUpdating = True
End Sub

I found this script to remove trailing commas, which also worked well for me.

Sub CommaKiller()


    Dim TextLine As String, comma As String
    comma = ","
  
    Close #1
    Close #2
   
    Open "C:\test\input.csv" For Input As #1
    Open "C:\test\output.csv" For Output As #2
   
    Do While Not EOF(1)
        Line Input #1, TextLine
       
        l = Len(TextLine)
        For i = 1 To l
            If Right(TextLine, 1) = comma Then
                TextLine = Left(TextLine, Len(TextLine) - 1)
            End If
        Next
       
        Print #2, TextLine
    Loop

    Close #1
    Close #2
   
End Sub

My problem is trying to combine these into one script. I tried calling Commakiller as a subroutine right after the csv is closed and using xStrCSVFName as the input. I also tried just pasting the code in rather than using it as a subroutine. Both times the code ran without errors but didn't remove the trailing commas. I know there have been a lot of previous questions about removing or preventing trailing commas in csv, but I have basically no coding experience so I'm struggling with this. Is there an easy way to combine these scripts or should I find another way to do this?

If I understand your issue, you want to pass the correct file name into the sub but don't know how to define parameters within subs.

If thats the issue it is extremely easy to solve:

You can add parameters into the declaring statement for the sub like so:

Sub CommaKiller(ByRef InputFile As String, ByRef OutputFile As String)

You can then change the two referenced paths to be your parameters:

    Open InputFile For Input As #1
    Open OutputFile For Output As #2

But that Sub could be improved. What if, for example, you wanted the output to be in the same file as input? Here is how I would write it:

Sub CommaKiller(ByRef InputFile As String, Optional OutputFile As String)
    If OutputFile = "" Then OutputFile = InputFile
    
    Dim comma As String, i As Long, j As Long
    comma = ","
   
    Dim FileNum As Long
    FileNum = FreeFile
    
    'Open Input File and count the number of lines
    Open InputFile For Input As #FileNum
    
    Dim LineCount As Long, LineText As String
    While Not EOF(FileNum)
        LineCount = LineCount + 1
        Line Input #FileNum, LineText
    Wend
    
    Close #FileNum
    
    'Fill an array with the text from each line
    Open InputFile For Input As #FileNum
    
    Dim InLines() As String
    ReDim InLines(LineCount - 1)
    
    While Not EOF(FileNum)
        Line Input #FileNum, InLines(i)
        i = i + 1
    Wend
    Close #FileNum
    
    'Open the output file (Which can be the same as the input file)
    Open OutputFile For Output As #FileNum
   
    For i = LBound(InLines) To UBound(InLines)
        l = Len(InLines(i))
        For j = 1 To l
            If Right(InLines(i), 1) = comma Then
                InLines(i) = Left(InLines(i), Len(InLines(i)) - 1)
            End If
        Next
       
        Print #FileNum, InLines(i)
    Next i

    Close #FileNum
   
End Sub

Which you can now call with the line Call CommaKiller "FullFilePathOfInput", "FullFilePathOfOutput" or if you want the output in the same file, you can omit the second argument and simply write Call CommaKiller "FullFilePathOfInput" . Where the FullFilePath means something like "C:\\Users\\Me\\Documents\\VBA\\MyCSVFile.csv" .

As for how to combine it into your code above... you would just need to insert a line after the xObjWB.SaveAs like Call CommaKiller xStrCSVFName & ".csv"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM