将一组参数传递给CallByName VBA

时间:2016-03-30 15:38:51

标签: arrays vba callbyname

我正在使用callByName I VBA来动态调用类的不同方法。根据方法的不同,我将有一个不同数量的参数,这些参数将保存在一个数组中。不幸的是,CallByName接受一个param数组,因此传递一个变量号并不简单。有没有解决方法,我找到了使用类型信息库的解决方案,但这似乎不适用于VBA,即使我已将其添加为参考。下面是我想要的例子

 public class CategoryModel
    {

        public int CategoryId { get; set; }
        public string CategoryName { get; set; }

        public ItemModel Item { get; set; }

    }


public class ItemModel
    {
        public int ItemId { get; set; }
        public int CategoryId { get; set; }
        public string ItemName { get; set; }

    }

2 个答案:

答案 0 :(得分:4)

通过更改方法签名,可以将CallByName与数组一起使用:

#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

以下是一个用法示例:

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

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

  CallByName2 obj, "MyMethod", arguments
End Sub

答案 1 :(得分:0)

你不能动态动态地,因为不同的方法需要不同数量的参数,你不能在不期望的地方传递参数。

如果您知道所需的参数数量,那么您可以调用数组的每个项目并传递:

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

但您可能需要设置Select Case块或类似物来处理所有不同的方法:

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

这很容易变得混乱。

相关问题