Excel将导出中的单元格删除为CSV

时间:2018-03-22 14:59:21

标签: excel export-to-csv

我在Excel中有一个表,我必须导出到CVS。表格如下:

https://kubernetes.io/docs/concepts/workloads/controllers/cron-jobs/#writing-a-cron-job-spec

我有以下代码导出到CSV:

Columns("A:D").Copy
Workbooks.Add
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="C:\x_test.csv" _
    , FileFormat:=xlCSV, CreateBackup:=False
ActiveWindow.Close
Application.DisplayAlerts = True

输出如下:

Book Title,,,
Author,Total Pages,Editor,Year Published
Adam,50,Universal,2018
Section,Pages,,
1,20,,
2,30,,

我遇到的问题是它在行中添加了我不需要的其他单元格。例如,第一行应该像"书名"不喜欢"书名,,,"

有没有办法导出到CSV,相应的列数正确反映每行的逗号

我尝试在Excel中合并单元格,但它没有任何区别。

1 个答案:

答案 0 :(得分:0)

根据@ cybernetic.nomad的建议,我已使用以下代码解决了该问题:

Sub Example()
'Final string to print to file
Dim strFinal As String
'Line read from original text file
Dim strLine As String
'open the text file for reading
Open "C:\x_test.csv" For Input As #1
strFinal = ""
'loop until the end of the text file is reached
While EOF(1) = False
'read the current line from the text file
    Line Input #1, strLine
    'remove the commas
    If InStr(strLine, ",,,") > 0 Then
        strFinal = strFinal + Replace(strLine, ",,,", "") + vbCrLf 
    ElseIf InStr(strLine, ",,") > 0 Then
        strFinal = strFinal + Replace(strLine, ",,", "") + vbCrLf
    Else
        strFinal = strFinal + strLine + vbCrLf
    End If

Wend
strFinal = Left(strFinal, Len(strFinal) - 2)
'close the file
Close #1

'open the file for writing
Open "C:\x_test.csv" For Output As #1
Print #1, strFinal
'overwrite the file with the new string
Close #1
End Sub