I am attempting to import a string as a formula into VBA, modify that formula based on certain conditions (ultimately to be defined by the user), and then evaluate that formula numerically for the rest of my code.
I tried writing to a text file and reading back from it.
I tried multiple different formats for a formula in Excel that could be read and then evaluated ("X+Y",X+Y,"=X+Y",=X+Y). When I read in the formula directly from the spreadsheet, it is an array of strings:
Mass_Balances = Worksheets("Formulas").Range("B3:C4").Value
Debug.Print Mass_Balances(1, 1)
(mu * Comp(2, 1) / (K_s + Comp(2, 1)) * Comp(1, 1)) - b * Comp(1, 1)
This is good, as I want to modify these formulae, which can only be done if it stays a string.
However, when I type out the text of one of those formulae and assign it to another variable, it is a double (since all the variables in it are defined). This is what I eventually want, once the formulae (a set of mass balances) is complete.
Var = (mu * Comp(2, 1) / (K_s + Comp(2, 1)) * Comp(1, 1)) - b * Comp(1, 1)
Debug.Print Var
9705.5737704918
When I try to assign the text of one of those formulae (an element of Mass_Balances) and assign it to another variable (such as Var), it either remains a string, or if the variable I am assigning to was declared as a double, I get a type mismatch (to be expected!). Converting to a double also doesn’t work (not that I expected it to).
Var = Mid(Mass_balances(1, 1), 2)
Debug.Print Var
(mu * Comp(2, 1) / (K_s + Comp(2, 1)) * Comp(1, 1)) - b * Comp(1, 1)
Using Mid here gets rid of the leading equals sign, which I thought was necessary to have it be a formula and able to be evaluated.
I realize the equations for both Var and Mass_Balances(1,1) are the same, when I said earlier that I wanted to revise the equations and then get the value. However, I figured if I can’t figure a way to numerically evaluate the original formula, trying to do so after updating it would also be fruitless.