Search code examples
powershellvb6

"Eval" functionality in VB6: replace VBScript by Powershell or some other means


Within a VB6 program, I have been using VBScript, to evaluate numerical math-expressions contained in strings.

(The string are generated by a programmed, string-based, algebraic manipulation algorithm which replaces algebraic variables in a math-expression by numerical values in order to check the results).

The evaluation of a numerical math-expression string is illustrated in the following code:-

vb6
    mathEx$="(1+2)*(5^2)"
    Set ob = CreateObject("MSScriptControl.ScriptControl")
    ob.Language = "VBScript"
    result = ob.eval(mathEx$) '---> 75

Now (October 2023) that VBScript is officially to be excluded from future Windows releases, I wonder whether and how Powershell (or some other means) could be used to provide this functionality (from within the VB6 program)?

EDIT 1 This question is NOT answered by this question which does not talk about accessing Powershell from VB6 at all.

EDIT 2 I have refocussed the question away from just Powerscript to open it up to other tools/methods.


Solution

  • Here is a simple Eval function which uses JET engine (MS Access) expression evaluator to do the job

    Option Explicit
    
    Private Function Eval(sExpression As String) As Variant
        Static oConn        As Object
        Dim sConnStr        As String
        
        If oConn Is Nothing Then
            sConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & Environ$("TEMP") & "\~eval.tmp"
            On Error Resume Next
            CreateObject("ADOX.Catalog").Create sConnStr
            On Error GoTo 0
            Set oConn = CreateObject("ADODB.Connection")
            oConn.Open sConnStr
        End If
        With oConn.Execute("SELECT " & sExpression)
            Eval = .Fields(.Fields.Count - 1).Value
        End With
    End Function
    
    Private Sub Form_Load()
        Debug.Print Eval("5 AS x, 2 AS y, sin(1+2)*(x^y)")
    End Sub