【问题标题】:VBA To Write CSV Format to Text File - 2 Snagging PointsVBA 将 CSV 格式写入文本文件 - 2 个问题
【发布时间】:2015-10-28 15:21:45
【问题描述】:

目前正在尝试从 excel 生成 CSV 格式的文本文件。

下面的代码可以很好地适应我突出显示的范围。但是,我现在发现有两个阻碍点使请求与标准 CSV 文本文件略有不同。

是否可以用双引号将数字以及任何未填充的字段括起来?

例如。期望的结果:

"测试","","1","2","3"

而不是:

“测试”,,1,2,3

下面的当前 VBA。我不确定对此的改变一定是答案,但我真的被困住了。

Dim myFile As String
Dim rng As Range
Dim cellValue As Variant
Dim i As Integer
Dim j As Integer

myFile = Application.DefaultFilePath & "\test.txt"
Set rng = Selection
Open myFile For Output As #1

For i = 1 To rng.Rows.Count
For j = 1 To rng.Columns.Count

cellValue = rng.Cells(i, j).Value

If j = rng.Columns.Count Then
Write #1, cellValue
Else
Write #1, cellValue,

End If

Next j
Next i

Close #1

提前致谢

【问题讨论】:

标签: excel csv export-to-csv vba


【解决方案1】:

试试这样的。

If j = rng.Columns.Count Then
    Write #1, """" & cellValue & """"
Else
    Write #1, """" & cellValue & """",
End If

如果文本单元格以某种方式已经得到了双引号,并且您不想得到 ""text"",那么您可能需要检查它们是否为 null 或数字。

If j = rng.Columns.Count Then
    if IsEmpty(cellValue) = true or isnumeric(cellValue) = true then
        Write #1, """" & cellValue & """"
    else
        Write #1,cellValue
    End if
Else
    if IsEmpty(cellValue) = true or isnumeric(cellValue) = true then
        Write #1, """" & cellValue & """", 
    else
        Write #1, cellValue, 
    End if
End If

【讨论】:

    【解决方案2】:

    MatthewD,太棒了。

    我变了:

    If j = rng.Columns.Count Then
    Write #1, """" & cellValue & """"
    Else
    Write #1, """" & cellValue & """",
    End If
    

    到:

    If j = rng.Columns.Count Then
    Write #1, "" & cellValue & ""
    Else
    Write #1, "" & cellValue & "",
    End If
    

    而且效果很好。感谢您的帮助并指出显而易见的问题。

    【讨论】:

    • 很高兴为您提供帮助。有时是两个双引号得到一个单引号,有时是四个。我认为这取决于你用它做什么。
    猜你喜欢
    • 2015-04-28
    • 2010-09-14
    • 1970-01-01
    • 2021-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-10
    • 1970-01-01
    相关资源
    最近更新 更多