【问题标题】:Export data as double with VBA使用 VBA 将数据导出为双精度
【发布时间】:2018-12-10 20:46:04
【问题描述】:

我想将所选数据从 Excel 工作表导出到简单的 txt 文件。 A 列必须导出为 INT,B 列为 String,C 列为 INT,D 列为 String,E 列为 Double(导出时必须将数据保存为 double 格式 - 35.50、30.00、0.00) 您可以查看附件图片以获取更多信息。 A.B,C,D 列很好,但我不能强制将 E 列值作为双精度提取到 txt 文件(在 excel 中,此列看起来很好 - 例如 35.00,但提取到 txt 文件的时间是 35 ) 这是我的 VBA 脚本:

Rem Attribute VBA_ModuleType=VBADocumentModule
Option VBASupport 1
Option Explicit

Private Sub CommandButton1_Click()  
    Dim myFile As String, rng As Range, cellValue As Variant, i As Integer, j As Integer

    myFile = Application.DefaultFilePath & "\rezultat.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 
End Sub

这就是我的 txt 文件中的结果:

1,"1144641",1,"NAME-STRING VALUE",350.5

Everythink 很好,除了最后一个值:必须是 350.50 可以看一下附件中的截图

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    将值格式化为在写入文件时显示 2 位小数

        If j = rng.Columns.Count Then
            Write #1, Format(cellValue, "#.00")
            'or Format(cellValue, "Standard")
        Else
            Write #1, cellValue,
        End If
    

    这是因为,默认情况下,只写入单元格的值/内容,而不是单元格格式。


    如果您希望避免将值写为带引号的字符串,那么您可以构造一个字符串来为每一行写入,而不是迭代行和列。例如,

    cellValues = rng.Cells(i, 1).Value & ",""" & rng.Cells(i, 2).Value & """," _ 
        & ... & Format(rng.Cells(i, 5), "#.00")
    

    双引号 "" 是嵌入引号所必需的。

    【讨论】:

    • 您还可以研究 Excel 的数据导出选项,而不是迭代行和列。
    • 谢谢,但是这样将最后一列导出为字符串:“350.50”,我想导出为数字 350.50,不带引号.....
    • @MiroslavKostadinov 我已添加到我的答案中。
    猜你喜欢
    • 2016-07-15
    • 2017-07-18
    • 2021-08-25
    • 2017-09-29
    • 2015-09-13
    • 2011-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多