Passing an array of Arguments to CallByName VBA

后端 未结 2 410
生来不讨喜
生来不讨喜 2020-12-21 12:53

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 a

2条回答
  •  执念已碎
    2020-12-21 13:56

    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
    

提交回复
热议问题