如何使VBA类方法返回对象

时间:2018-09-01 13:50:07

标签: vba class

我写了一个表示几何向量的类(由x和y坐标定义),我想通过简单的翻译使其方法之一返回类似类型的对象

Cass的名称为Vxy,其代码为:

Option Explicit
''+------------------------------------------------------------------+
''| Class Vector defined by x and y                                  |
''+------------------------------------------------------------------+
Private px As Double: Private py As Double
Public Property Get x() As Double:    x = px:            End Property
Public Property Let x(d As Double):  px = d:             End Property
Public Property Get y() As Double:    y = py:            End Property
Public Property Let y(d As Double):  py = d:             End Property
''+------------------------------------------------------------------+
''| Method Translation                                               |
''|                                                                  |
''+------------------------------------------------------------------+
Function Ts(V As Vxy) As Vxy 
 Set Ts = CreateObject("Vxy")
 Ts.x = Me.x + V.x
 Ts.y = Me.y + V.y
End Function

试图创建上述类的对象的代码如下:

Option Explicit
''+------------------------------------------------------------------+
''| Testing Vectors                                                  |
''|                                                                  |
''+------------------------------------------------------------------+
Sub test_Vectors()
Dim V As New Vxy
 V.x = 3
 V.y = 4:
MsgBox V.a:
MsgBox V.l: ' Ok
Dim V_translated As New Vxy: V_translated = V.Ts(V) 'ERROR HERE
MsgBox V_translated.x: MsgBox V_translated.y:
End Sub

错误是:运行时错误429:ActiveX组件无法创建对象

2 个答案:

答案 0 :(得分:2)

您不能使用CreateObject("Vxy")绑定到本地类(这会引发429错误)

Set Ts = new Vxy

您还需要Set对象引用,这样:

Set V_translated = V.Ts(V)

答案 1 :(得分:2)

CreateObject("Vxy")将尝试在注册表中查找对象的CSLID,以实例化该对象的后期绑定实例。它在VBA中运行,因此显然不会被注册。只需将其替换为早期绑定版本:

Set Ts = New Vxy