首页 > 解决方案 > 在 R1C1 公式中使用时,带小数的变量会转换为 2 位数字

问题描述

所以我的问题很简单。在我的 VBA 代码中,我从 3 个单元格中检索 3 个值。在下面的示例中,Value1 = 110,5;Value2=100;Value3=120

        Value1 = Worksheets(Countryname).Cells(k, 5).Value
        Value2 = Worksheets(Countryname).Cells(k, 14).Value
        Value3 = Worksheets(Countryname).Cells(k, 23).Value
        Cells(k, 4).Formula = "=MIN(" & Value1 & "," & Value2 & "," & Value3 & ")"

由于未知原因,Excel 中显示的结果如下:

=MIN(110;50;100;130), instead of MIN(110,5;100;130)

问题在于第一个变量被转换为 2 个变量(110,5 转换为 110;5)

你有解决这个问题的办法吗?

在此先感谢您的帮助!

标签: vbaexcel

解决方案


Your comma-as-decimal-placeholder is conflicting with the default EN-US list separator. Use .FormulaLocal and write the formula as it would appear to you on the worksheet.

dim value1 as string, value2 as string, value3 as string
Value1 = Worksheets(Countryname).Cells(k, 5).text
Value2 = Worksheets(Countryname).Cells(k, 14).text
Value3 = Worksheets(Countryname).Cells(k, 23).text
Cells(k, 4).FormulaLocal = "=MIN(" & Value1 & ";" & Value2 & ";" & Value3 & ")"
'alternate with qualified cell addresses
Cells(k, 4).formula = "=min(" & Worksheets(Countryname).Cells(k, 5).address(external:=true) & "," & _
                                Worksheets(Countryname).Cells(k, 14).address(external:=true) & "," & _
                                Worksheets(Countryname).Cells(k, 23).address(external:=true) & ")"

Looking at the way you're using k, it could easily be inferred that you are running a loop like for k=2 to lastRow. If that is the case, then write all of the formulas at once.

with range(Cells(2, 4), cells(lastRow, 4))
    .formula = "=min(" & Worksheets(Countryname).Cells(2, 5).address(0, 1, external:=true) & "," & _
                                Worksheets(Countryname).Cells(2, 14).address(0, 1, external:=true) & "," & _
                                Worksheets(Countryname).Cells(2, 23).address(0, 1, external:=true) & ")"
end with

If you are hard-coding values into the worksheet formula, you might as well just write the result value in.

Cells(k, 4) = application.min(Worksheets(Countryname).Cells(k, 5).value2, _
                              Worksheets(Countryname).Cells(k, 14).value2, _
                              Worksheets(Countryname).Cells(k, 23).value2)

推荐阅读