如何让VBA Class方法返回一个对象

问题描述 投票:1回答:2

我写了一个代表几何Vector的类(由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组件无法创建对象

vba class
2个回答
2
投票

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

Set Ts = New Vxy

2
投票

你不能迟到绑定到本地类与CreateObject("Vxy")(这会引起你的429错误):

Set Ts = new Vxy

您还需要Set对象引用,以便:

Set V_translated = V.Ts(V)
© www.soinside.com 2019 - 2024. All rights reserved.