Evaluate string formulas in VB

If you've come to Visual Basic from Microsoft Access, you probably
miss the handy Eval() method. This method evaluates a supplied
string as though it were code. As a result, you could easily
evaluate mathematical expressions passed as a string, like so:

iResult = Eval("(2 * 3) + 5)")

which fills iResult with the value 11.

To achieve this same functionality in Visual Basic, you've no doubt
resorted to complicated string parsing functions.  Or perhaps you
added Access' DLL to your project, which may have seemed like an
awful lot of DLL for such a simple method.

Now, though, you'll be happy to know that you can use the
Eval() method without a lot of overhead. Microsoft provides this
functionality in its Script Control. This very lightweight ActiveX
component is available so you can add end-user scripting ability
to your applications.  However, as a result, it also comes with
an Eval method. Adding this component to your project provides
very little overhead and gives you the ability to evaluate
mathematical strings.

To download this OCX, visit http://msdn.microsoft.com/scripting/
Select the Script Control link, then follow the Download
instructions. The following code shows the simple VB we added
to a command button's click event. The SC1 script control
evaluates a mathematical formula in the txtFormula textbox.

Private Sub Command1_Click()
MsgBox txtFormula & " = " & SC1.Eval(txtFormula)
End Sub

You might also like...

Comments

ElementK Journals

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone” - Bjarne Stroustrup