【问题标题】:How to use .numberformat in VBA with variable of type double as comperator如何在 VBA 中使用 .numberformat 并将 double 类型的变量用作比较器
【发布时间】:2021-03-16 11:17:12
【问题描述】:

亲爱的,我想根据单元格值格式化我的单元格。有 3 种可能的条件:

Cell is larger than 0.05 -> the Value should stay the same but be fromated to 0.0
Cell is smaller than a variable (called Threshold) -> the Value should be replaced with a String "a.C."
Cell is Zero -> the Value should be replaced with a Dash"

我想出了如何在没有 here 的变量的情况下做到这一点。讨论如何在vba中添加文本字符串.numberformathere

这个:

.NumberFormat = "[=0]---;[<0.05] ""a.C."";0.0 "

确实有效,而这个:

Dim threshold as Double

threshold = 0.05

.NumberFormat = "[=0]---;[<threshold] ""a.C."";0.0 "

不起作用。我想我需要将一个特殊的变量拼写错误传递给“

非常感谢您的提示! 提前谢谢你

【问题讨论】:

    标签: excel vba number-formatting


    【解决方案1】:

    那是因为threshold 是您的数字格式字符串的一部分。基本上,引号内的所有内容都不会被 VBA 触及 - 除了告诉 VBA 在字符串中使用引号字符而不是结束字符串的双双引号。

    要将变量的内容放入字符串,请使用字符串连接。这是在 VBA 中使用“&”运算符完成的:

    .NumberFormat = "[=0]---;[<" & threshold & "] ""a.C."";0.0 "
    

    但是,由于四舍五入,Double 可能有点讨厌,因此最好使用 format 命令以所需的形式输出它(例如小数点后 2 位)。使用一个可以通过调试器轻松检查的中间变量通常是个好主意:

    Dim myNumberFormat as string
    myNumberFormat  = "[=0]---;[<" _
                    & format(threshold, "0.00") _
                    & "] ""a.C."";0.0 "
    .NumberFormat = myNumberFormat  
    

    【讨论】:

    • 您好,谢谢您的回答。不幸的是,这不起作用。 d.dd 将变量格式化为某种类型的 Date 我猜?但即使我这样做&amp; format(threshold, "0.00") _ 传递给 excel 的 Numberformat 读取[=0]---;[&lt;0] "a.C.";0.0 如果我通过右键单击-> 格式检查我尝试更改的单元格值?
    • 变量 myNumberFormat 读取:[=0]---;[&lt;0,05]"a.C.";0.0 如果我打印它。所以缺少两个引号,并且有一个逗号而不是“点”。如果我手动将其更改为 "[=0]---;[&lt;0.05]""a.C."";0.0" 并使用字符串 dirclty 它可以工作。
    • 对不起,我的错误,应该是“0.00”。更正了我的答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-20
    • 2016-08-26
    • 2016-01-13
    • 2016-01-02
    • 2016-10-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多