2013-07-29 80 views
0

所以我基本都在Excel中從日曆中包含的數據行的列表,所有誰創造了他們每個用戶。我正在爲每個用戶製作一個對象集合。在將個人添加到第1個集合後,我在用戶對象內部創建了另一個名爲「Events」的集合。這是存儲事件類型和日期的地方。我無法將數組添加到Collection「Events」中。添加陣列收集VBA

「用戶」對象是這樣的:

User

-Name

-Events [event1, event2, event3, ..., etc]

我得到的錯誤「對象變量或帶變量未設置」這是在結束從下面的代碼所採取的行的neested 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 

如果這樣做的任何更簡單的方法,或者如果這是不可能的,請點我在正確的方向。任何幫助是極大的讚賞。謝謝。

+1

在構造你的'User'對象,你'初始化Events' ? – sigil

回答

0

在用戶類中添加方法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 
+2

這是不正確的。對象可以用Dim'語句初始化;作爲一個例子,嘗試用'Dim FSO作爲New FileSystemObject'創建一個新的FileSystemObject。沒有'Set'語句就可以立即使用。 – sigil

+1

@sigil我建議你去閱讀:http://support.microsoft.com/kb/154651 – Sorceri

+0

初始化是問題。對不起,第一次使用VBA時,我發現所有創建類的教程都很糟糕。謝謝您的幫助! – hartley054