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
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
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.