简体   繁体   中英

#VALUE Error in Evaluate Function of Excel VBA

I am trying to find out what is wrong with the process below. In my sheet, there is a formula string which needs evaluation for different values of variable, x .

(0.5*(23-9.81)*3*(x^2))*(x/3)+(0.5*9.81*(x^2))*(x/3)-1*((0.5*18.5*0.33*(2.5^2))*(x+2.5/3)+(18.5*0.33*2.5*x)*(x/2)+(0.5*(23-9.81)*0.33*(x^2))*(x/3)+(0.5*9.81*(x^2))*(x/3)+(100*0.33*(2.5+x))*((2.5+x)/2))

I have a vba code which looks like this:

Public Function ev(r As Range, x As Double) As Variant
    ev = Application.Evaluate(Replace(r.Value, "x", x))
End Function

What's weird is that this function only works if the cell input is like

=ev(Q25,10.01)

but not

=ev(Q25,10.000000001)

or even

=ev(Q25,10.00001)

Why is this happening? I need the program to calculate using small increments of up to 0.0000000001 . Thank you for your insights.

There is a 255 character limit to a String passed to Application.Evaluate . You're running into that hard limit after Replace ing x with the corresponding numeric value.

Your options include:

  • Breaking up the formula into pieces and Evaluate ing it in several steps.
  • Rewriting the formula to something shorter as mentioned in the comments (though you may still surpass the 255 limit based on length of the proposed arguments).
  • Using an approach like this and writing the revised formula to a cell, then reading back the calculated value.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM