Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleEvaluate mathematical expressions using the MS Script control
DescriptionThis example shows how to evaluate mathematical expressions using the MS Script control in Visual Basic 6.
Keywordsmathematical expression, expression, evaluate, parse, Script control
CategoriesAlgorithms, 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
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated