带有变量运算符的Excel VBA数学类型公式对十进制数不起作用

时间:2018-01-17 08:09:18

标签: excel vba excel-vba operators

我有一个小脚本,用于执行简单的数学运算,其中运算符被定义为变量。唯一的问题是它只适用于整数,而不是十进制数。任何人都知道为什么? 我试图将运算符和数字分成两个变量,但问题仍然存在。

Sub CellMath2()
Call CreateSheetBackup
Dim rng As Range
Dim expression As Variant
expression = InputBox("Enter operator (* / + - ^) and number (e.g. ""*1000"").", "Operator and number")
If StrPtr(expression) = 0 Then Exit Sub
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
    rng.Value = "=" & rng & expression
    rng.Value = rng.Value
Else
End If
Next rng
End Sub

3 个答案:

答案 0 :(得分:1)

尝试在inputbox之后使用以下行:

If Application.ThousandsSeparator = " " Then expression = Replace(expression, " ", "")
If Application.DecimalSeparator = "," Then expression = Replace(expression, ",", ".")

答案 1 :(得分:1)

您正在寻找的是Evaluate方法。

使用方式:

For Each rng In Selection
    If WorksheetFunction.IsNumber(rng) Then
        rng.Value = Evaluate(Replace(rng & expression, ",", "."))
    End If
Next rng

Evaluate接受与公式相同的运算符样式,至少在很大程度上,所以如果A1的值为10expression="+10",那么{{} 1}}会给你Evaluate(Range("A1") & expression

20将欧洲小数转换为美国标准(VBA使用)。

答案 2 :(得分:0)

我可以将运算符和数字分开并使用case select语句,但是我必须包含所有可能的运算符,并将功能限制为我包含的运算符。

这适用于输入框和单元格中的十进制逗号:

Sub CellMath()
Dim rng As Range
Dim c As Variant, operator As Variant
operator = InputBox("Enter operator (* / + - ^ or e).", "Operator")
If StrPtr(operator) = 0 Then Exit Sub
c = InputBox("Enter number.", "Number")
If StrPtr(c) = 0 Then Exit Sub
For Each rng In Selection
If WorksheetFunction.IsNumber(rng) Then
Select Case operator
    Case "*"
    rng.Value = rng * c
    Case "/"
    rng.Value = rng / c
    Case "+"
    rng.Value = rng + c
    Case "-"
    rng.Value = rng - c
    Case "^"
    rng.Value = rng ^ c
    Case "e"
    rng.Value = rng * 10 ^ c
End Select
Else
End If
Next rng
End Sub

我忘记了哪些有趣的运营商?