A simple expression evaluator

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 IfEnd 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 ScriptControlDim sExpr As String

oScriptCtl.Language = "VBScript"sExpr = "sqr(25)+2^2+((3+7)/5+1)"MsgBox sExpr & " = " & oScriptCtl.Eval(sExpr)

Share the Post:
Heading photo, Metadata.

What is Metadata?

What is metadata? Well, It’s an odd concept to wrap your head around. Metadata is essentially the secondary layer of data that tracks details about the “regular” data. The regular

XDR solutions

The Benefits of Using XDR Solutions

Cybercriminals constantly adapt their strategies, developing newer, more powerful, and intelligent ways to attack your network. Since security professionals must innovate as well, more conventional endpoint detection solutions have evolved

AI is revolutionizing fraud detection

How AI is Revolutionizing Fraud Detection

Artificial intelligence – commonly known as AI – means a form of technology with multiple uses. As a result, it has become extremely valuable to a number of businesses across

AI innovation

Companies Leading AI Innovation in 2023

Artificial intelligence (AI) has been transforming industries and revolutionizing business operations. AI’s potential to enhance efficiency and productivity has become crucial to many businesses. As we move into 2023, several

data fivetran pricing

Fivetran Pricing Explained

One of the biggest trends of the 21st century is the massive surge in analytics. Analytics is the process of utilizing data to drive future decision-making. With so much of

kubernetes logging

Kubernetes Logging: What You Need to Know

Kubernetes from Google is one of the most popular open-source and free container management solutions made to make managing and deploying applications easier. It has a solid architecture that makes

ransomware cyber attack

Why Is Ransomware Such a Major Threat?

One of the most significant cyber threats faced by modern organizations is a ransomware attack. Ransomware attacks have grown in both sophistication and frequency over the past few years, forcing