Is there something wrong with the scriptcontrol.eval method?

Gruff
09-05-2003, 12:10 PM
I was going to use the scriptcontrol.eval method as a simple way for a user to enter formula expressions. For example. "(2.548 + .125) / 2"

Sure enough it does this very well. Unfortunately it also will accept
undefined characters as though they were variables or something.
For example it happily takes (A1 + 7 + 3 - Dog) and returns 10

Why????

Is there some way to force the method to be more strict or to fire a trappable error???

I am having visions of a user flubbing up a key when entering numbers.

Any help understanding this thing would be great.

-Tom

Thinker
09-05-2003, 12:21 PM
The script control only works with script (surprise). There is only one
variable type in VBScript, the Variant. A1 will just evaluate to a variant
variable with the value of 0 and the same with Dog.

Gruff
09-06-2003, 02:36 PM
Ah! So then VB script is like Visual Basic without 'Option Explicit' Declaration. Right? Is this an optional feature? Is there some way to add 'Option Explicit' so that the EVAL method throws a compile error?

"Variable not defined."

Durn! ... Hey! I suppose I could write a filter to pre-process the input.
Something like:


Option Explicit

Public XVal As Double

Public Function CalculatorFilter(ByVal s_Expression As String) As String
Dim s As String

'Remove acceptable characters and strings
s = UCase(s_Expression)
s = Replace(s, "SIN", "")
s = Replace(s, "COS", "")
'Add more Desired functions here
s = Replace(s, "(", "")
s = Replace(s, ")", "")
s = Replace(s, "+", "")
s = Replace(s, "-", "")
s = Replace(s, "/", "")
s = Replace(s, "*", "")
s = Replace(s, "^", "")
s = Replace(s, ".", "")
s = Replace(s, "1", "")
s = Replace(s, "2", "")
s = Replace(s, "3", "")
s = Replace(s, "4", "")
s = Replace(s, "5", "")
s = Replace(s, "6", "")
s = Replace(s, "7", "")
s = Replace(s, "8", "")
s = Replace(s, "9", "")
s = Replace(s, "0", "")
s = Replace(s, " ", "")

If s = "" Then
'Everything is good
CalculatorFilter = s_Expression
Else
'Force an error that script will see:
'"Unterminated string constant"
CalculatorFilter = Chr(34) & "A"
End If
End Function

Private Sub ScriptControl1_Error()
MsgBox "Unrecognised Component in Formula"
txtXVal.selStart = ScriptControl1.Error.Column
End Sub

Private Sub txtXVal_KeyDown(KeyCode As Integer, Shift As Integer)

If KeyCode = vbKeyReturn Then
On Error GoTo MathErr
XVal = ScriptControl1.Eval(CalculatorFilter(txtXVal.Text))
txtXVal.text = XVal
DoSomethingHere (XVal)
End If

Exit Sub
MathErr:
'Clear regular system error
Err.Clear
End Sub


This works, and saves the time needed to write a parser from scratch.

I am not so sure about the best place to trap the Error though.
What do you think?

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum