VBA - Evaluate Conditions as String

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

提交回复
热议问题