【问题标题】:How to read the formatted percentage from a cell with VBA?如何使用 VBA 从单元格中读取格式化百分比?
【发布时间】:2016-01-21 19:50:35
【问题描述】:

我正在从 Excel 电子表格中获取数据并将其插入到 Word 文档中。这是我正在使用的代码,它按预期工作。

Private Sub insertData(wb As Excel.Workbook)
    Dim numBM As Integer
    Dim countBM As Integer
    Dim currentBM As String

    numBM = ActiveDocument.Bookmarks.Count

    For countBM = 1 To numBM
        currentBM = ActiveDocument.Bookmarks(countBM).Name
        ActiveDocument.Bookmarks(currentBM).Range.Text = wb.Names(currentBM).RefersToRange.Value2
    Next
End Sub

在 Excel 中,我有一些采用百分比格式的单元格。所以单元格的值为 0.857394723 但单元格显示“86%”。如何更改我的代码,以便将“86%”插入 Word 而不是“0.857394723”

【问题讨论】:

  • 不知道为什么这个问题会被否决。以目前的形式,它似乎是一个有效的问题(没有太多的代码、明确的问题、没有太多的上下文……)。我认为我们有责任在拒绝投票时发表评论(尤其是对新用户),让他们学习和改进。无论如何,我的 +1 会让你回到中立分数 :-)

标签: excel vba ms-word format percentage


【解决方案1】:

使用 VBA 标准库中的 Strings.Format 方法相应地格式化值:

Dim formattedValue As String
formattedValue = Format(wb.Names(currentBM).RefersToRange.Value2,"0%")

ActiveDocument.Bookmarks(currentBM).Range.Text = formattedValue

【讨论】:

  • 感谢您的回答。我试过了,它确实有效,但我必须扩展我的代码来格式化一些值而不是其他值。
【解决方案2】:

我实际上已经找到了答案,这非常简单。而不是使用 ...RefersToRange.Value 我可以使用 ...RefersToRange.Text 所以该行变为

ActiveDocument.Bookmarks(currentBM).Range.Text = wb.Names(currentBM).RefersToRange.Text

【讨论】:

    猜你喜欢
    • 2017-08-08
    • 2019-07-03
    • 2014-01-26
    • 2021-01-15
    • 2020-10-02
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多