In Cell(1,1) of one sheet, I have this formula: 5 * a ^ 2 + 3 * a ^ 1 + 1 * a + 5
In Cell(2,1) of the same sheet, I have another formula: 3 * b ^ 2 + 5 * b ^ 1 + 1 * b + 3
I want to calculate values for these formulas and assign it to variables within VBA. For example, I've been trying something like this
Function calculate_y(a,b)
answer1 = [A1]
answer2 = [A2]
calculate_y = answer1 + answer2
End Function
But I keep getting errors. I have tried playing around with Evaluate() and characters like & but to no avail. The reason I'm not directly entering the formulas into vba is because these formulas will be changing. I don't want to have to update the formulas manually.
Use evaluate while replacing the variables in the string with the values provided:
Function calculate_y(a, b)
With Application.Caller.Parent
answer1 = .Evaluate(Replace(.Range("A1"), "a", a))
answer2 = .Evaluate(Replace(.Range("A2"), "b", b))
End With
calculate_y = answer1 + answer2
End Function
If you are not planning on using it as a UDF but calling it from vba, you should also pass the worksheet on which the formulas reside:
Function calculate_y(ws As Worksheet, a As Double, b As Double)
With ws
answer1 = .Evaluate(Replace(.Range("A1"), "a", a))
answer2 = .Evaluate(Replace(.Range("A2"), "b", b))
End With
calculate_y = answer1 + answer2
End Function
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.