在Excel VBA中工作,我正在尝试初始化类的几个对象的数组" CUserType",但我遇到了一些麻烦。我尝试在循环中执行此操作,如下所示:
For count = 1 To size
Dim myArray(count) As CUserType
Next
但是,看起来VBA希望数组索引是一个常量整数。
现在我尝试使用单独的函数来完成它,如下所示:
Sub ititUsers(num As Integer)
Dim myArray() As CUserType
Redim myArray(1 to num)
If num = 1 Then
Dim myArray(1) As CUserType
ElseIf num = 2 Then
Dim myArray(1) As New CUserType
Dim myArray(2) As New CUserType
ElseIf num = 3 Then
Dim myArray(1) As New CUserType
Dim myArray(2) As New CUserType
Dim myArray(3) As New CUserType
.
.
.
End Sub
但当然这既乏味又浪费。我是新手,所以我知道我可能会遗漏一些东西。有什么帮助吗?
谢谢!
答案 0 :(得分:2)
您的行Dim myArray(count) As CUserType
已将数组的所有元素设置为CUserType。如果您只需要初始化它,那么执行For循环:
Sub ititUsers(num As Integer)
Dim i As Long
Dim myArray() As CUserType
Redim myArray(1 to num)
For i = 1 to num
Set myArray(i) = New CUserType
Next i
End Sub