|
|
Title | Evaluate mathematical expressions using the MS Script control |
Description | This example shows how to evaluate mathematical expressions using the MS Script control in Visual Basic 6. |
Keywords | mathematical expression, expression, evaluate, parse, Script control |
Categories | Algorithms, Strings |
|
|
When the user clicks the Evaluate button, the program creates a new MS Script control and sets its language to VBScript. It then generates lines of code that assign values to variables entered by the user. It makes a function that returns the value of the expression entered by the user and uses the control's Eval method to evaluate the function.
|
|
' Evaluate the expression entered by the user.
Private Sub CmdEvaluate_Click()
Dim script_control As MSScriptControl.ScriptControl
Dim i As Integer
Dim name As String
Dim value As String
Dim rslt As Variant
' Make a script control.
Set script_control = New MSScriptControl.ScriptControl
script_control.Language = "VBScript"
' Make code to set the primative values.
For i = 0 To 4
name = Trim$(NameText(i).Text)
value = Trim$(ValueText(i).Text)
If name <> "" And value <> "" Then
script_control.AddCode name & " = " & value
End If
Next i
' Make the function.
script_control.AddCode _
"Function TheFunction()" & vbCrLf & _
" TheFunction = " & txtExpression.Text & vbCrLf _
& _
"End Function"
' Evaluate the expression.
txtResult.Text = ""
On Error GoTo EvaluateError
rslt = script_control.Eval("TheFunction()")
txtResult.Text = Format$(rslt)
Exit Sub
EvaluateError:
Beep
MsgBox Err.Description
End Sub
|
|
|
|
|
|