将 excel 文件保存为 csv VBA 时的三重引号

Triple Quotes when saving an excel file as csv VBA

我在将 excel 文件另存为 CSV 文件时在每个单元格上得到三重引号,它需要像 "Hello World" 但我在打开时得到 """Hello World""" CSV 文件。 CSV 文件以逗号分隔

编辑:如果我不带引号保存它,它的保存就像 Hello world

Do While xExcelFile <> ""
    newFileName = Replace(xExcelFile, " ", "_")

'*****************************************************
    For Each c In Range("A1").CurrentRegion
        If Not IsNumeric(c.Value) Then
            c.Value = Chr(34) & c.Value & Chr(34)
        End If
    Next c
'******************************************************
    'Saving file as csv
SaveFile:
    ActiveWorkbook.SaveAs fileName:=xSPath & newFileName & ".csv", FileFormat:=xlCSV, CreateBackup:=False
    ActiveWorkbook.Close

    'workbooks transformed log into cells
    Cells(cont, 6).Value = newFileName
    cont = cont + 1

NextLoop:
    'next file
    xExcelFile = Dir
Loop

使用这部分代码:

'*****************************************************
    For Each c In Range("A1").CurrentRegion
        If Not IsNumeric(c.Value) Then
            c.Value = Chr(34) & c.Value & Chr(34)
        End If
    Next c
'******************************************************
    'Saving file as csv
SaveFile:
    ActiveWorkbook.SaveAs Filename:=ActiveWorkbook.Path & "\teststs" & ".csv", FileFormat:=xlCSV, CreateBackup:=False

我的文件按预期保存了一组双引号...所以问题可能出在您的代码中的其他地方。你保存的路径是什么?它与您从中加载 excel 文件的文件夹相同吗?

认为您可能也在循环浏览 CSV,因此需要额外的引号...

试试这个

Sub test()
    Dim xSpath As String
    Dim newFileName As String
    Dim rngDB As Range
    xSpath = ThisWorkbook.Path & "\"
    newFileName = "test1"

    Set rngDB = Range("a1").CurrentRegion
    TransToCsv rngDB, XPath & newFileName & ".csv"
End Sub

Sub TransToCsv(rngDB As Range, strFile As String)
    Dim vDB, vR() As String, vTxt()
    Dim i As Long, j As Integer
    Dim objStream
    Dim strTxt As String

    Set objStream = CreateObject("ADODB.Stream")

    vDB = rngDB

    For i = 1 To UBound(vDB, 1)
        n = n + 1
        ReDim vR(1 To UBound(vDB, 2))
        For j = 1 To UBound(vDB, 2)
            If IsNumeric(vDB(i, j)) Then
                vR(j) = vDB(i, j)
            Else
                vR(j) = Chr(34) & vDB(i, j) & Chr(34)
            End If
        Next j
        ReDim Preserve vTxt(1 To n)
        vTxt(n) = Join(vR, ",")
    Next i
    strTxt = Join(vTxt, vbCrLf)
    With objStream
        '.Charset = "utf-8"
        .Open
        .WriteText strTxt
        .SaveToFile strFile, 2
        .Close
    End With
    Set objStream = Nothing

End Sub