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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With