advertisement
Premier Club Log In/Registration
  Include Code  Search Tips
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   SKILLBUILDING  |   TIP BANK  |   SOURCEBANK  |   FORUMS  |   NEWSLETTERS
Browse DevX
Partners & Affiliates
advertisement
advertisement
Tip of the Day
Average Rating: 4/5 | Rate this item | 1 user has rated this item.
Tip formerly from VB2TheMax
Expertise: Intermediate
Language: VB4,VB5,VB6
October 6, 2001
A simple expression evaluator
While any Windows user could pop up the Calculator accessory to perform any type of math calculations, it would be great if you could offer him or her the capability to do simple math from within your application. This is a very simple expression evaluator function that does it:

Function EvalExpression(ByVal expression As String) As Double
    Dim result As Double
    Dim operand As Double
    Dim opcode As String
    Dim index As Integer
    Dim lastIndex As Integer
    
    ' the null character mark the end of the string
    expression = expression & vbNullChar
    
    For index = 1 To Len(expression) + 1
        If InStr("+-*/" & vbNullChar, Mid$(expression, index, 1)) Then
            If lastIndex = 0 Then
                ' this is the first operand in the expression
                result = Val(Left$(expression, index - 1))
            Else
                ' extract the new operand
                operand = Val(Mid$(expression, lastIndex, index - lastIndex))
                ' execute the pending operation
                Select Case opcode
                Case "+"
                    result = result + operand
                Case "-"
                    result = result - operand
                Case "*"
                    result = result * operand
                Case "/"
                    result = result / operand
                End Select
            End If
            opcode = Mid$(expression, index, 1)
            lastIndex = index + 1
        End If
    Next
    EvalExpression = LTrim$(result)
    
End Function
This evaluator is very simple, and has a number of limitations: it does not account for negative numbers nor for parenthesis and sub-expressions, and operands are evaluated from left to right without any priority rule (e.g. "10+2*3" returns 36, and not 16). Nevertheless it is very handy and lets you make you program friendlier to your customer by adding the capability to perform calculation from within a textbox control. This routine shows how to evaluate the expression in a textbox control when the user presses the F2 key:

Sub Text1_KeyDown (KeyCode As Integer, Shift As Integer)
    If KeyCode = vbKeyF2 And Shift = 0 Then
        Text1.Text = EvalExpression(Text1.Text)
        Text1.SelStart = Len(Text1.Text)
    End If
End Sub
If you want to evaluate more complex expressions you can use the MS Script Control library, which offers a simple way to do it. This control has an Eval method that evaluates any expression, with parenthesis, sub-expressions, math functions such as sqr, power, etc., and evaluates the operators in the right order. Add the "Microsoft Script Control" library from the References dialog window, and execute the following code to calculate the result of the given sample expression: Dim oScriptCtl As New ScriptControl Dim sExpr As String

oScriptCtl.Language = "VBScript"
sExpr = "sqr(25)+2^2+((3+7)/5+1)"
MsgBox sExpr & " = " & oScriptCtl.Eval(sExpr)
Francesco Balena
If you have a hot tip and we publish it, we'll pay you. However, due to accounting overhead we no longer pay $10 for a single tip submission. You must accumulate 10 acceptable tips to receive payment. Be sure to include a clear explanation of what the technique does and why it's useful. If it includes code, limit it to 20 lines if possible. Submit your tip here.
advertisement
Untitled
advertisement
Advertising Info  |   Member Services  |   Permissions  |   Contact Us  |   Help  |   Feedback  |   Site Map  |   Network Map  |   About


JupiterOnlineMedia

internet.comearthweb.comDevx.commediabistro.comGraphics.com

Search:

Jupitermedia Corporation has two divisions: Jupiterimages and JupiterOnlineMedia

Jupitermedia Corporate Info


Legal Notices, Licensing, Reprints, & Permissions, Privacy Policy.

Advertise | Newsletters | Tech Jobs | Shopping | E-mail Offers

Solutions
Whitepapers and eBooks
Intel PDF: Virtualization Delivers Data Center Efficiency
Intel eBook: Managing the Evolving Data Center
Microsoft Article: BitLocker Brings Encryption to Windows Server 2008
Symantec eBook: The Guide to E-Mail Archiving and Management
Microsoft Article: RODCs Transform Branch Office Security
Go Parallel Article: James Reinders on the Intel Parallel Studio Beta Program
Avaya Article: Advancing the State of the Art in Customer Service
Adobe Acrobat Connect Pro: Web Conferencing and eLearning Whitepapers
Avaya Article: Avaya AE Services Provide Rapid Telephony Integration with Facebook
Go Parallel Article: Getting Started with TBB on Windows
HP eBook: Storage Networking , Part 1
MORE WHITEPAPERS, EBOOKS, AND ARTICLES
Webcasts
Intel Seminar: Efficiencies in Hardware/Software Virtualization
HP Webcast: Disaster Recovery Planning
Go Parallel Video: Performance and Threading Tools for Game Developers
HP Video: StorageWorks EVA4400 and Oracle
HP Webcast: Storage Is Changing Fast - Be Ready or Be Left Behind
MORE WEBCASTS, PODCASTS, AND VIDEOS
Downloads and eKits
IBM TCO eKIT: Your IT Budget is Under Attack, Get in Control
IBM Energy Efficiency eKIT: Learn How to Reduce Costs
30-Day Trial: SPAMfighter Exchange Module
Red Gate Download: SQL Toolbelt and free High-Performance SQL Code eBook
Iron Speed Designer Application Generator
MORE DOWNLOADS, EKITS, AND FREE TRIALS
Tutorials and Demos
Microsoft Article: Silverlight Streaming--Free Video Hosting for All
Featured Algorithm: Intel Threading Building Blocks - parallel_reduce
HP Demo: StorageWorks EVA4400
MORE TUTORIALS, DEMOS AND STEP-BY-STEP GUIDES