One obvious syntax error: The And operator does NOT execute two statements on the same line, so the statement
does not end up in Products and Reactants each containing the value 1. And is a boolean operator for testing two boolean statements with And logic. This statement takes the value 1(True) and the expression reactants=1 (reactants is 0 so this evaluates to False), then evaluates the overall boolean expression (True and False is False) and assigns that result to Products. Products now contains the value False/0, so it has not changed (and reactants has not changed either).
The way to join to statements on one line in VBA is by separating the statements with ":" so
Even with that change, the code does not seem to be converging on anything. The values for Products and Reactants and amount_reacted all seem to grow without bound, so the loop runs until it reaches an overflow error. I find -- especially with a brute force algorithm like this -- that I must understand the behavior of the objective function in order to put together a good, working algorithm. I edited your code to provide a means of analyzing the objective function in the spreadsheet:
Running the procedure through 20 loops now gives me a table of values that shows how the objective function (total_K-amount_reacted) and the other key variables are behaving during each iteration. If desired, you can insert a scatter chart (column S against column O) to visualize the behavior on a chart. It should be immediately obvious after only a few iterations that the values are growing without bound.
Putting my chemist hat on for a moment, it looks like you have a simple reaction like A+B->2C where 1 mole of A combines with 1 mole of B to give 2 moles of C. Your "experiment" shows 35 moles of A and 20 moles of B, and your goal is to figure out where the reaction ends up from that starting place (how many moles of C is produced and how many moles of A and B will be left over at the end). How am I doing so far? In terms of the variables in your program, Reacted and amount_reacted somehow measure the extent of reaction. Reactants and Products, I would guess, are related to the moles of reactants and products present during that iteration/test case. Am I understanding so far?
If I have mostly understood, then the observation that reactants, products, etc. grow without bound suggests to me that your procedure is failing to account for a material balance step. It seems like your procedure needs to somehow constrain the reactants, products, amount_reacted, etc. by the 55 total moles of reactants available or the 20 moles of limiting reactant available (or something). I don't fully understand the meanings of your variables or the exact procedure you are wanting to use to determine the extent of reaction, but it feels like you need to think more carefully through your chemistry until you get better expressions/loops for products, reactants, amount_reacted, etc.
Bookmarks