Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
611 views
in Technique[技术] by (71.8m points)

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

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 class at run time.

This time, however, I'm trying to figure out how to get an object at run time from a string.

For example, let's say I have a string with the following data: Worksheets("RAW DATA").Range("A1").QueryTable.

Here's what I might try to do where the data above is the input for strParam below:

Function GetObject(strParam As String) As Object
    GetObject = SomeFunction(strParam)
End Function

In this case, GetObject should return a QueryTable when evaluated against Worksheets("RAW DATA").Range("A1").QueryTable. Is there anything in VBA that could take the place of SomeFunction from the example above?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...