【问题标题】:Excel remove cells in export to CSVExcel 删除导出到 CSV 的单元格
【发布时间】:2018-03-22 14:59:20
【问题描述】:

我在 Excel 中有一个表,我必须将其导出到 CVS。表格是这样的:

我有以下代码要导出到 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 中合并单元格,但没有任何区别。

【问题讨论】:

  • 它没有添加单元格,单元格那里(只有它们是空的)。您可能需要在保存后浏览 csv 以删除多余的逗号。
  • 好的,谢谢您的建议

标签: excel export-to-csv


【解决方案1】:

根据@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

【讨论】:

    猜你喜欢
    • 2018-06-24
    • 2015-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-01
    • 2020-09-22
    • 2016-10-14
    • 1970-01-01
    相关资源
    最近更新 更多