Your request is kind of vague and generic, so I'm not sure what specific response to give. How much of your question is about loop structures? How much is about the broader root finding algorithm? How much is just how to make a UDF? Have you looked z=f(x,y) and determined that a numerical algorithm is needed -- that you cannot solve for x or y at a given z algebraically?
If your question is more about how to make a UDF, I might suggest my tutorial here: https://www.excelforum.com/tips-and-...uild-udfs.html
If your question is more about loops in VBA, this looks good: https://trumpexcel.com/vba-loops/
If your question is more about loops in root finding algorithms, I put together a simple UDF that uses the Newton-Raphson method to find roots of cubic polynomials (2D function) (https://www.excelforum.com/tips-and-...ml#post4688682 ) that should illustrate the use of a For..Next loop in one root finding algorithm.
Function NRcuberoot(xi As Double, a As Double, b As Double, c As Double, d As Double) As Double
'Because this receives parameters as doubles, it should be faster than the other function.
'However, it is limited to cubic (or smaller) polynomials. It is not flexible.
Dim xnew As Double, xold As Double, f As Double, df As Double
Dim i As Integer
'initialize loop
xnew = xi
For i = 1 To 100 'max iteration is 100
xold = xnew
f = a + b * xnew + c * xnew ^ 2 + d * xnew ^ 3
df = b + 2 * c * xnew + 3 * d * xnew ^ 2
xnew = xnew - f / df
'If converged exit loop and finish
If Abs(xnew - xold) < 0.000001 Then Exit For
Next i
'normally I would include a block to return an error if the loop did not converge (if i>=100)
NRcuberoot = xnew
End Function
I would also ask if you are required to use VBA for this? For years, VBA has been talked about as a dying programming language. MSFT has even started trying to steer people towards a new "office add-ins" model based on other, more enduring programming languages (like Javascript). Where you are new to VBA, it may be advantageous to consider whether your time would be better spent learning a programming language that is less likely to be decommissioned soon. As an old dog not learning new tricks, I have no idea how one would build a UDF in the new model, but I could see some value in learning the new ways rather than learning the old ways.
I know that isn't very specific, but maybe it will provide an opportunity for further feedback. How can we help you move forward?
Bookmarks