[英]Debug.Print Item of 2D Collection
我最終設法用每個條目兩個變量填充一個Collection。 為此,我定義了一個名為“ DataRange”的類模塊,它看起來像這樣:
Public Strain As Double
Public Stress As Double
這是我填充收藏集的方式:
Sub ECalc()
Dim j As Integer
Dim mycol As Collection
Dim c As DataRange
Set mycol = New Collection
Set c = New DataRange
For j = 1 To 200
c.Strain = Sheets("Data").Range("I" & j).Value2
c.Stress = Sheets("Data").Range("K" & j).Value2
mycol.Add c
Next j
Debug.Print mycol.Count ' <--- This does work, I can see how many entries have been created (200 as stated by j = 200)
Debug.Print mycol.Item(20) ' <--- This does not work. WHY?
End Sub
當我通過“ mycol.Count”獲得許多條目時,代碼確實填充了我的收藏集。 但是,我無法訪問代碼的最后一行中的單個項。 出現錯誤,指出:“運行時錯誤438對象不支持此屬性或方法”
我究竟做錯了什么?
額外信息:我不想使用數組,因為我打算在后續步驟中調整集合的大小。
編輯以擴大我在OP代碼中發現的問題的答案
這是因為
mycol.Item(20)
您引用的object
(類DataRange
的對象)的值不是“默認”
所以你必須編碼:
Debug.Print mycol.Item(20).Stress ' print the 'Stress' property of the 'DataRange' object stored as the 20th item of your collection
Debug.Print mycol.Item(21).Strain ' print the 'Strain' property of the 'DataRange' object stored as the 21th item of your collection
但是您必須在For
循環內移動Set c = New DataRange
語句,如下所示:
Sub ECalc()
Dim j As Long
Dim mycol As Collection
Dim c As DataRange
Set mycol = New Collection
For j = 1 To 200
Set c = New DataRange ' instantiate a new object of type 'DataRange' at every iteration
c.Strain = Sheets("Data").Range("I" & j).Value2 'assign current object 'Strain' property
c.Stress = Sheets("Data").Range("K" & j).Value2 'assign current object 'Stress' property
mycol.Add c ' add current object to the collection
Next
End Sub
否則,所有集合項都將引用您在For
循環之前實例化的SAME DataRange
對象,從而使它們全部具有從I和K列的最后一個“數據”工作表行讀取的SAME Strain
和Stress
屬性
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.