2
在VBA类中处理模块级数组的正确方法是什么?在VBA类中处理模块级数组的正确方法是什么?
我使用Property Let
和Property Get
其他变量,但我还没有想出如何传递数组和从属性。
已更新。此代码对Mark Nold感谢。
Option Explicit
Private mstrTestArray() As String
Public Property Get TestArray() As String()
TestArray = mstrTestArray
End Property
Public Property Let TestArray(ByRef strTestArray() As String)
mstrTestArray = strTestArray
End Property
Public Property Get TestArrayValue(d1 As Long, d2 As Long) As String
TestArrayValue = mstrTestArray(d1, d2)
End Property
Public Property Let TestArrayValue(d1 As Long, d2 As Long, strValue As String)
strTestArray(d1, d2) = strValue
End Property
Sub DoTest()
Dim strTestArray() As String
ReDim strTestArray(2, 1) As String
strTestArray(0, 0) = "a": strTestArray(0, 1) = "one"
strTestArray(1, 0) = "b": strTestArray(1, 1) = "two"
strTestArray(2, 0) = "c": strTestArray(2, 1) = "three"
TestArray = strTestArray
Debug.Print TestArrayValue(UBound(TestArray, 1), UBound(TestArray, 2))
End Sub
以下不起作用。这个顶部在上述类中的方法:
Sub LetArrayFromReference(ByRef strTestArray() As String)
TestArray = strTestArray
End Sub
这部分是调用类的程序:
Sub DoTest()
Dim strTestArray() As String
ReDim strTestArray(2, 1) As String
Dim objTestClass As New TestClass
strTestArray(0, 0) = "a": strTestArray(0, 1) = "one"
strTestArray(1, 0) = "b": strTestArray(1, 1) = "two"
strTestArray(2, 0) = "c": strTestArray(2, 1) = "three"
objTestClass.LetArrayFromReference strTestArray
Debug.Print objTestClass.TestArrayValue(UBound(objTestClass.TestArray, 1) _
, UBound(objTestClass.TestArray, 2))
End Sub
谢谢!
这是我正在寻找的提示。你基本上必须为数组属性设置两组Let/Get。一个用于数组,另一个用于数组。我的代码中也有一个错字。谢谢马克! – Kuyenda 2009-12-17 05:50:07
Mark,我在我的问题中添加了一些代码(在“以下不起作用”之后)。你可以请评论为什么不能从方法参数设置数组属性?是否因为这样做试图从ByRef创建一个ByRef?谢谢! – Kuyenda 2009-12-18 02:06:24