我使用Excel工作表作为计算工具。此工具作为多重输入(比如在单元格A1到A10中)并计算最后的成本(单元格B1)。我现在想用这个工具来分析各种场景,即当我改变一个或多个输入时的成本是多少。
因此,我想在VBA中编写一个函数,我可以在其中指定要修改的单元格以及这些单元格的值,并使用这些新值作为输入复制B1的值。例如:
=my_function(B1,A4;a_value_for_A4;A7;a_value_for_A7).
我尝试了以下代码。当我在一个单元格中尝试它时它可以正常工作,但是当我手动更改输入值时会使excel崩溃。
Function calculate(ParamArray var() As Variant) As Double
' 1st arg : cell with result to copy
' 2nd arg : cell to modify
' 3rd arg : cell with new value for 2nd arg
' 4th, resp. 5th... : like 2nd, resp. 3rd args
Dim old_values() As Double
Dim res As Double
ReDim old_values(UBound(var) - LBound(var))
For i = 0 To (UBound(var) - LBound(var) - 1) \ 2
old_values(i) = var(LBound(var) + 2 * i + 1).Value
Next i
For i = 0 To (UBound(var) - LBound(var) - 1) \ 2
Evaluate "modify_cell_val(" & var(LBound(var) + 2 * i + 1).Address(False, False) & "," & var(LBound(var) + 2 * i + 2).Value & ")"
Next i
res = var(LBound(var)).Value
For i = 0 To (UBound(var) - LBound(var) - 1) \ 2
var(LBound(var) + 2 * i + 1).Value = old_values(i)
Evaluate "modify_cell_val(" & var(LBound(var) + 2 * i + 1).Address(False, False) & "," & old_values(i) & ")"
Next i
calculate = res
End Function