您可以尝试创建属性来访问您的类实例中的私有 Matrix 字段。属性允许您定义私有类字段的公共接口。保持矩阵私有,但给它一个唯一的名称,例如:
Private pMatrix(6, 14) As String
唯一的名称允许您在 Get 和 Let 属性中使用更直观的名称。这些属性允许您分别定义读取和写入接口,可能如下所示:
Public Property Let Matrix(i As Integer, j As Integer, value As String)
pMatrix(i, j) = value
End Property
Public Property Get Matrix(i As Integer, j As Integer) As String
Matrix = pMatrix(i, j)
End Property
您可以将它们直接放在类模块中的字段声明下方。
最后,您可以从工作表子例程中删除.Value 方法,pMatrix 字段不包含此方法。 = 告诉编译器您希望调用 Let 属性,它将两个属性参数 (0, 0) 作为属性 i 和 j 中的前两个参数以及右侧的值赋值为第三个参数value。
我修改后的代码全部列在下面:
****clsStudent****
Option Explicit
Public ID As Integer
Public Name As String
Public Teacher As String
Private pMatrix(6, 14) As String
Public Property Let Matrix(i As Integer, j As Integer, value As String)
pMatrix(i, j) = value
End Property
Public Property Get Matrix(i As Integer, j As Integer) As String
Matrix = pMatrix(i, j)
End Property
****clsStudent****
****Module1****
Option Explicit
Public Arr As Variant
****Module1****
****Sheet1****
Option Explicit
Sub test()
Dim i As Integer, k As Integer
i = 20
ReDim Arr(0 To (i)) As clsStudent ' array with students size
For k = 0 To i
Set Arr(k) = New clsStudent
Next k
Arr(0).ID = 123
Arr(0).Matrix(0, 0) = "123" 'no error here anymore
Debug.Print Arr(0).Matrix(0, 0)
End Sub
****Sheet1****
对于信息,Module1 代码不是必需的。
***已编辑以包含 shA.t 关于变量声明的评论