VBA中CallByName的使用示例

分类:代码, 博客 标签:

VBA中CallByName函数是一个灵活性很强的函数,通过它可以实现通过字符串调用方法以及回调的功能,这里给出一个使用示例,具体应用具体分析并实现。

首先,定义一个类模块,并起名为CMyObject,类实现代码如下:

Option Explicit
Private MyPropValue As Integer

Public Function Multiply(x As Integer, y As Integer) As Integer
   Multiply = x * y
End Function

Public Property Get MyProperty() As Variant
   MyProperty = MyPropValue
End Property

Public Property Let MyProperty(ByVal vNewValue As Variant)
   MyPropValue = vNewValue
End Property

然后是调用CallByName函数测试,代码如下:

Private Sub Test()
   Dim myclass As New CMyObject
   Dim sum As Integer
   Dim prop As Integer

   ' Example of calling a method with CallByName
   ' equivalent to -- sum = myclass.Multiply(12, 12)
   sum = CallByName(myclass, "Multiply", VbMethod, 12, 12)
   MsgBox sum

   ' Example of a property let with CallByName
   ' equivalent to -- myclass.MyProperty = 5
   CallByName myclass, "MyProperty", VbLet, 5

   ' Example of a property get with CallByName
   ' equivalent to -- prop = myclass.MyProperty
   prop = CallByName(myclass, "MyProperty", VbGet)
   MsgBox prop
End Sub


分类:代码, 博客 标签:

发表评论

You must be logged in to post a comment.