我在 A 列中有带有
8,753 - 1,087*4 + 0,1784*5*5 + 0,3447*4*4
等表达式的行
我想让 VBA 计算 B 列中的结果值。
谁能推荐一下?
我尝试了 VBA 评估函数,但结果出错,我在 excel 中尝试了间接的,我试图在 VBA 中插入一个“=”——也无济于事。目前,只有手动转到单元格并在每一行输入 = 才有效,但我有 20000 行这样的行,无法更改输入源或格式。必须有更好的方法来做到这一点......
如果字符串包含有效计算,
Application.Evaluate
将起作用。但是,VBA 假定数字使用的是小数点,而不是逗号(逗号被解释为参数分隔符)——这就是您收到错误 2015 的原因。
所以也许使用这样的功能:
Function CalculateFormula(ByVal f As String)
f = Replace(f, ",", ".")
CalculateFormula = Application.Evaluate(f)
End Function
尝试:
Public Sub test()
Dim i As Long, LastRow As Long
'Refer to the specific worksheet
With ThisWorkbook.Worksheets("Sheet1")
'Get last row of column A
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
'Loop all values
For i = 1 To LastRow
'Replace extra spaces with nothing, replace "," with "." and evaluate the formula
.Range("B" & i).Value = Evaluate(Replace(Replace(.Range("A" & i).Value, ",", "."), " ", ""))
Next i
End With
End Sub
您必须使用 VBA 遍历 A 列中的每一行,计算每一行的表达式,然后将结果输入 B 列。为了帮助您,请考虑以下示例:
Sub Values()
Dim lastRow As Long
Dim i As Long
Dim formula As String
Dim result As Variant
lastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To lastRow
formula = Range("A" & i).Value
result = Evaluate(formula)
Range("B" & i).Value = result
Next i
End Sub