VBA - Evaluate Conditions as String

前端 未结 2 1996
执笔经年
执笔经年 2021-01-14 22:04

I have come across a very strange scenario. In a function I will receive a string of condition to be evaluated.

E.g.

(a>b and (b=2 or c!=3))
         


        
2条回答
  •  庸人自扰
    2021-01-14 22:30

    Alternative way, add a reference to Microsoft Script Control

    Dim vx As MSScriptControl.ScriptControl
    Set vx = New MSScriptControl.ScriptControl
    
    a = 100
    b = 200
    c = 300
    Cond = "(a>b and (b=2 or c<>3))"
    
    With vx
        .Language = "VBScript"
        .AddCode "function stub(a,b,c): stub=" & Cond & ": end function"
    
        result = .Run("stub", a, b, c)
    End With
    
    MsgBox result
    

    Note you will need to replace != with <> as the former is not valid in VB* (and and/or is not valid in jScript)

提交回复
热议问题