繁体   English   中英

VBA 将多个 Excel 文件转换为 CSV 并删除尾随逗号

[英]VBA convert multiple Excel files to CSV and remove trailing commas

我有大量的 xlsx 报告,我需要将它们转换为 csv 以导入到另一个程序中。 但是,当 Excel 转换它们时,它会添加尾随逗号,以防止软件读取文件。

我在网上找到了这个脚本,可以将整个文件夹的文件转换为 csv,它对我来说效果很好。

    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

我发现这个脚本可以删除尾随逗号,这对我来说也很好用。

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

我的问题是试图将这些组合成一个脚本。 我尝试在关闭 csv 并使用 xStrCSVFName 作为输入后立即将 Commkiller 作为子例程调用。 我还尝试只粘贴代码而不是将其用作子例程。 两次代码都没有错误地运行,但没有删除尾随逗号。 我知道之前有很多关于在 csv 中删除或防止尾随逗号的问题,但我基本上没有编码经验,所以我正在努力解决这个问题。 有没有一种简单的方法来组合这些脚本,或者我应该找到另一种方法来做到这一点?

如果我理解您的问题,您想将正确的文件名传递到 sub 中,但不知道如何在 subs 中定义参数。

如果这就是问题,那么解决起来非常容易:

您可以将参数添加到 sub 的声明语句中,如下所示:

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

然后,您可以将两个引用的路径更改为您的参数:

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

但是那个 Sub 可以改进。 例如,如果您希望输出与输入在同一个文件中怎么办? 这是我将如何编写它:

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

您现在可以使用Call CommaKiller "FullFilePathOfInput", "FullFilePathOfOutput"Call CommaKiller "FullFilePathOfInput", "FullFilePathOfOutput"或者如果您希望在同一文件中输出,则可以省略第二个参数,只需编写Call CommaKiller "FullFilePathOfInput" FullFilePath 的意思类似于"C:\\Users\\Me\\Documents\\VBA\\MyCSVFile.csv"

至于如何将它组合到你上面的代码中......你只需要在xObjWB.SaveAs之后插入一行,比如Call CommaKiller xStrCSVFName & ".csv"

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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