问题
I'm getting triple quotes on each cell when saving an excel file as CSV, it needs to be like "Hello World"
but I'm getting """Hello World"""
when I open the CSV file. the CSV is comma delimited
edit: if I save it without the quotes, its save like 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
回答1:
Try this
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
回答2:
Using this part of your code:
'*****************************************************
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
My file saves fine with one set of double quotes as expected... so maybe the problem lies somewhere else within your code. What is the path you are saving to? Is it the same as the folder you are loading the excel files from?
Thinking you might be looping through the CSV's as well, hence the extra quotes...
来源:https://stackoverflow.com/questions/53451389/triple-quotes-when-saving-an-excel-file-as-csv-vba