VBA - Evaluate Conditions as String

前端 未结 2 1970
执笔经年
执笔经年 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:23

    Here's a proper answer to your question, rather than just a comment.

    You need to:

    • Set a reference to Microsoft Visual Basic for Applications Extensibility x.x (Tools/References) in the VBIDE.
    • Trust access to the VBA project object model (use Google to find out how to do this for your version of Excel).
    • Run initValues() then call getConstantValue("(a>b and (b=2 or c<>3))")

    Code:

    Option Explicit
    
    Dim a As Long
    Dim b As Long
    Dim c As Long
    
    Sub initValues()
        a = 3
        b = 2
        c = 4
    End Sub
    
    Function getConstantValue(constStr As String) As Variant
    
        Dim oMod As VBIDE.CodeModule
        Dim i As Long, _
            num As Long
    
        Set oMod = ThisWorkbook.VBProject.VBComponents("Module1").CodeModule
    
        For i = 1 To oMod.CountOfLines
            If oMod.Lines(i, 1) = "Function tempGetConstValue() As Variant" Then
                num = i + 1
                Exit For
            End If
        Next i
    
        oMod.InsertLines num, "tempGetConstValue = " & constStr
    
        getConstantValue = Application.Run("tempGetConstValue")
    
        oMod.DeleteLines num
    
    End Function
    
    Function tempGetConstValue() As Variant
    End Function
    
    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题