Jehannum_2000
New Member
- Joined
- Sep 14, 2024
- Messages
- 15
- Office Version
- Prefer Not To Say
- Platform
- Windows
I have a simple function which is meant to evaluate a numerical expression input by the user:
When the user enters a simple number, not an expression, the function sometimes works and sometimes doesn't work.
In particular, the numbers 1, 3, 5, 7, 60, 124 and 125 give an error (Type Mismatch, I think). All other positive integers up to 126 work perfectly.
However, if I include the following line in the function (before Application.Evaluate) it always works without an error:
I guessed the above fix, but don't really understand why it works.
Are the 'forbidden' numbers numbers that were previously entered at some point that Excel doesn't want to evaluate again for efficiency reasons? If so, why does appending "+ 0" cause them to work?
I would like to understand a little more about what's going on. Any help appreciated!
VBA Code:
Function eval(n As String) As Double
'Evaluates numeric expression contained in string n
Application.Volatile
On Error GoTo Handle_Error: 'need handler for /0 exceptions etc. from user input
eval = Application.Evaluate(n)
Exit Function
Handle_Error:
MsgBox ("Incorrect expression.")
eval = 0
End Function
When the user enters a simple number, not an expression, the function sometimes works and sometimes doesn't work.
In particular, the numbers 1, 3, 5, 7, 60, 124 and 125 give an error (Type Mismatch, I think). All other positive integers up to 126 work perfectly.
However, if I include the following line in the function (before Application.Evaluate) it always works without an error:
VBA Code:
n = n & "+0"
I guessed the above fix, but don't really understand why it works.
Are the 'forbidden' numbers numbers that were previously entered at some point that Excel doesn't want to evaluate again for efficiency reasons? If so, why does appending "+ 0" cause them to work?
I would like to understand a little more about what's going on. Any help appreciated!