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