Monday, June 15, 2015

VB.Net - Function Evaluate Formula in String

VB.Net - Function Evaluate Formula in String

This function will evaluate formula, example : vString = "( 4 + 5 ) * 2"
Dim xValue as Integer = 0
Dim xFormula as string = "( 4 + 5 ) * 2"
xValue = MyEval(xFormula)

Step 1 : Add Reference in your VB
c:\windows\sysem32\msscript.ocx



Step 2 : Copy Paste this code in your common module

'---- Add referense c:\windows\sysem32\msscript.ocx
Public Function MyEval(ByVal pFormula As String) As Integer
Dim SC As New MSScriptControl.ScriptControl
'Dim Formula As String = "(2+4)*5"
Dim Formula As String = pFormula
'SET LANGUAGE TO VBSCRIPT
SC.Language = "VBSCRIPT"
'ATTEMPT MATH
Try
Dim zResult As Double = Convert.ToDouble(SC.Eval(Formula))
'SHOW THAT IT WAS VALID
'MessageBox.Show("Math success, " & Formula & " equals " & zResult.ToString)
Return zResult
Catch ex As Exception
'SHOW THAT IT WAS INVALID
MessageBox.Show("Not a valid math formula for a double.")
End Try
Return Nothing
End Function

No comments:

Post a Comment