带有矩阵的Excel vba对象数组

时间:2015-04-09 12:19:17

标签: arrays excel vba excel-vba

我正在尝试创建一个对象数组。所有对象都来自同一个类。 我希望每个对象都有一个矩阵(二维数组)。但我无法做到这一点。

我在我的module1中有这个:

Public Arr As Variant

clsStudent类是:

Public ID As Integer
Public Name As String
Public Teacher As String
Private Matrix(6, 14) As String 

这是我的Sheet1子:

Dim i, 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).Value = "123"  'error here

最后一行给出了一个错误:

  

对象不支持此属性或方法

我尝试将矩阵更改为:

Public Matrix(6,14) as String

但是我收到了这个错误:

  

常量,固定长度字符串,数组,用户定义类型和声明语句不允许作为对象模块的公共成员

我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

我建议您使用此方法,而不是使用公共2D数组:

Public Function getMatrix(Bound1 As Integer, Bound2 As Integer) As String
    getMatrix = Matrix(Bound1, Bound2)
END Function

Public Sub setMatrix(Bound1 As Integer, Bound2 As Integer, mValue As String)
    Matrix(Bound1, Bound2) = mValue
END Function

  

<强> OUT-注意:
  Dim i, k As Integer相当于Dim i As Variant, k As Integer,并不等同于Dim i As Integer, k As Integer

使用Dim i As Integer, k As Integer

答案 1 :(得分:0)

您可以尝试创建属性以访问类实例中的私有Matrix字段。属性允许您定义私有类字段的公共接口。保持矩阵私有,但给它一个唯一的名称,如:

Private pMatrix(6, 14) As String 

唯一名称可让您在GetLet属性中使用更直观的名称。这些属性允许您分别定义读取和写入接口,可能如下所示:

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和{{1}中的前两个参数发送并将赋值右侧的值作为第三个参数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**** 代码。

***编辑包含shA.t关于变量声明的评论