在VBA类中处理模块级数组的正确方法是什么?

时间:2009-12-17 03:54:06

标签: arrays vba class properties

在VBA类中处理模块级数组的正确方法是什么?

我将Property LetProperty 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

谢谢!

1 个答案:

答案 0 :(得分:2)

下面的代码可能会为您提供一些帮助的线索。首先定义一个名为TestClass的类。

Option Explicit

Private strTestArray() As String

Public Property Get TestArrayValue(d1 As Long, d2 As Long) As String
    TestArrayValue = strTestArray(d1, d2)
End Property

Public Property Let TestArrayValue(d1 As Long, d2 As Long, sValue As String)
    strTestArray(d1, d2) = sValue
End Property


Sub DoTest()

    Dim myTestArray() As String
    ReDim myTestArray(3, 1) As String

    myTestArray(0, 0) = "a": myTestArray(0, 1) = "one"
    myTestArray(1, 0) = "b": myTestArray(1, 1) = "two"
    myTestArray(2, 0) = "c": myTestArray(2, 1) = "three"

    strTestArray = myTestArray
    Me.TestArrayValue(3, 1) = "Hello"


    Debug.Print strTestArray(2, 1)
    Debug.Print Me.TestArrayValue(1, 1)
    Debug.Print Me.TestArrayValue(3, 1)

End Sub

然后在代码模块或工作表中创建一个名为MyTest()的子<; p>

Option Explicit

Sub MyTest()
  Dim t As New TestClass
  t.DoTest  

  Debug.Print "The value at 1,1 is; " & t.TestArrayValue(1, 1)
End Sub

在课程中,您可以更新strTestArray()Me.TestArrayValue。我将让你为TestArray创建一个Get和set。我不是100%肯定你要做的事情。如果你有任何问题留下评论并更新你的OP:)