How can I evaluate a string into an object in VBA?

前端 未结 3 1369
無奈伤痛
無奈伤痛 2020-12-03 19:58

In my previous question, How do I assign a value to a property where the property name is supplied at runtime in VBA?, I learned to use CallByName to set a property in a cla

相关标签:
3条回答
  • 2020-12-03 20:11

    This time you're out of luck. There is no VBA equivalent of eval (not in Excel anyway...there is in Access VBA).

    (Application.Evaluate() evaluates strings as Excel expressions, not as VBA code.)

    0 讨论(0)
  • 2020-12-03 20:16

    Active Scripting Engine can help you. Instantiate ScriptControl ActiveX, use .AddObject() method to add reference to Excel's Application object to the script control's execution environment, set the third parameter to True to make all Application's members accessible too. Then just use .Eval() method to evaluate any property or method, which is the Application's member. The example below shows evaluation of Worksheets() property:

    Sub TestQueryTable()
        Dim objQueryTable As QueryTable
        Dim strEvalContent As String
        strEvalContent = "Worksheets(""RAW DATA"").Range(""A1"").QueryTable"
        Set objQueryTable = EvalObject(strEvalContent)
        objQueryTable.Refresh
        MsgBox objQueryTable.Connection
    End Sub
    
    Function EvalObject(strEvalContent As String) As Object
        With CreateObject("ScriptControl")
            .Language = "VBScript"
            .AddObject "app", Application, True
            Set EvalObject = .Eval(strEvalContent)
        End With
    End Function
    

    If you are on 64-bit Office, this answer may help you to get ScriptControl to work.

    0 讨论(0)
  • 2020-12-03 20:22

    There's the "Evaluate" method (or [ ] brackets). I don't think it will do exactly what you expect - as in run VBA code found in a string. You can look it up in the VBA help menu.

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