【问题标题】:Add array to Collection in VBA将数组添加到 VBA 中的集合
【发布时间】:2013-07-29 20:53:18
【问题描述】:

所以我基本上在 excel 中有一个行列表,其中包含来自日历的数据,所有这些都包含创建它们的每个用户。我正在为每个用户制作一个对象集合。将个人添加到第一个集合后,我在用户对象内有另一个名为“事件”的集合。这是存储事件类型和日期的地方。我在将数组添加到集合“事件”时遇到问题。

“用户”对象如下所示:

用户

-名称

-事件[event1, event2, event3, ..., etc]

我收到“对象变量或未设置变量”的错误 以下是在给出此错误的所需 if 和 else if 语句末尾的代码行:

temp.Events.Add arr1

emp2.​​Events.Add arr2

代码:

Do Until IsEmpty(Cells(i, 5))
Dim name As String
'grab name in cell
name = Cells(i, 5)
'if first list item, add new user
If list.Count = 0 Then
    Dim emp1 As New User
    emp1.name = name
    list.Add emp1
Else
    'traverse through list and search for same name
    For j = 1 To list.Count
        'if name is present, add event data to user object
        If list.Item(j).name = name Then
            Dim temp As New User
            Set temp = list.Item(j)
            Dim arr1(2) As String
            arr1(1) = Cells(i, 3)
            arr1(2) = Cells(i, 1)
            temp.Events.Add arr1
        'if name is not present, add new user and event data to new user object
        ElseIf j = list.Count Then
            Dim emp2 As New User
            emp2.name = name
            Dim arr2(2) As String
            arr2(1) = Cells(i, 3)
            arr2(2) = Cells(i, 1)
            emp2.Events.Add arr2
            list.Add emp2
        End If
    Next
End If

    i = i + 1
Loop

如果有任何更简单的方法可以做到这一点,或者如果这不可能,请指出正确的方向。任何帮助是极大的赞赏。谢谢。

【问题讨论】:

  • User 对象的构造函数中,是否初始化Events

标签: arrays vba collections


【解决方案1】:

在您的 User 类中添加方法 Class_Initialize 并初始化您的变量。现在这只在第一个使用的方法上被调用,所以当你使用

Dim temp As New User 

在调用对象的方法之前,它还没有被初始化。

在使用前你会想用下面的方式来初始化它

Dim temp As User
set temp = New User 'now it is initialized

在您的用户类中

Private Sub Class_Initialize()
'code here 
End Sub

【讨论】:

  • 这是不正确的。可以使用Dim 语句初始化对象;例如,尝试使用Dim FSO as New FileSystemObject 创建一个新的 FileSystemObject。无需Set 声明即可立即使用。
  • 初始化是个问题。抱歉,第一次使用 VBA,我能找到的所有创建类的教程都很糟糕。感谢您的帮助!
  • @Sorceri,你说得对,class_initialize() 直到第一个方法调用才会被调用——我不知道。但它也会在第一次属性调用之前被调用。您在 MS Support 中给出的示例是指在 class_initialize() 期间设置其值之前尝试访问全局属性,这确实是一个意想不到的问题。但在这种情况下,问题在于 User 类属性,因此在调用属性之前调用构造函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-08-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多