Passing an array of Arguments to CallByName VBA

五迷三道 提交于 2019-12-02 11:45:25

问题


I'm using callByName I VBA to dynamically call different methods of a class. Depending on the method, I will have a different number of arguments which will be held in an array. Unfortunately CallByName accepts a param array, therefore it's not straightforward to pass a variable number. Is there a way around this, I found a solution using the Type Information Library but this does not seem to work on VBA even though I have added it as a reference. Below is an illustration of what I want

 Public Sub Initialize_Object(ByRef TaskObject, Task_Collection)

 Dim Task_begin As Variant, Method_Parameters As Variant

 Task_begin = Task_Collection("Method")

 CallByName TaskObject, Task_begin, VbMethod, Method_Parameters

回答1:


You could use CallByName with an array as argument by changing the method signature :

#If VBA7 Or Win64 Then
  Private Declare PtrSafe Function rtcCallByName Lib "VBE7.DLL" ( _
    ByVal Object As Object, _
    ByVal ProcName As LongPtr, _
    ByVal CallType As VbCallType, _
    ByRef args() As Any, _
    Optional ByVal lcid As Long) As Variant
#Else
  Private Declare Function rtcCallByName Lib "VBE6.DLL" ( _
    ByVal Object As Object, _
    ByVal ProcName As Long, _
    ByVal CallType As VbCallType, _
    ByRef args() As Any, _
    Optional ByVal lcid As Long) As Variant
#End If

Public Function CallByName2(Object As Object, ProcName As String, args() As Variant)
   AssignResult CallByName2, rtcCallByName(Object, StrPtr(ProcName), VbMethod, args)
End Function

Private Sub AssignResult(target, result)
  If VBA.IsObject(result) Then Set target = result Else target = result
End Sub

Here is a usage example:

Sub UsageExample()
  Dim obj As Object, arguments()

  Dim obj As New Class1
  arguments = Array(1, 3)

  CallByName2 obj, "MyMethod", arguments
End Sub



回答2:


You can't do this dynamically because different methods will require a different amount of arguments and you can't pass arguments where they aren't expected.

If you know the amount of arguments required, then you could call each item of the array and pass that:

CallByName TaskObject, Task_begin, VbMethod, Method_Parameters(0), Method_Parameters(1), Method_Parameters(2)

but you would probably have to set up a Select Case block or similar to handle all the different methods:

Select Case Method_Name
    Case "Method_1": CallByName TaskObject, Task_begin, VbMethod, Method_Parameters(0), Method_Parameters(1)
    Case "Method_2": CallByName TaskObject, Task_begin, VbMethod, Method_Parameters(0)
    Case "Method_3": CallByName TaskObject, Task_begin, VbMethod, Method_Parameters(0), Method_Parameters(1), Method_Parameters(2)
End Select

Which can get messy quite easily.



来源:https://stackoverflow.com/questions/36313575/passing-an-array-of-arguments-to-callbyname-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!