Excel 调试。打印2D集合的项
我最终设法用每个条目两个变量填充了一个集合。为此,我定义了一个名为“DataRange”的类模块,如下所示:Excel 调试。打印2D集合的项,excel,vba,collections,Excel,Vba,Collections,我最终设法用每个条目两个变量填充了一个集合。为此,我定义了一个名为“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 =
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
Sub-ECalc()
作为整数的Dim j
Dim mycol As集合
dimcas数据范围
Set mycol=新集合
设置c=新数据范围
对于j=1到200
c、 应变=板材(“数据”).范围(“I”和“j”).值2
c、 应力=板材(“数据”).范围(“K”和j).值2
霉素c
下一个j
Debug.Print mycl.Count'编辑以放大我在OP代码中发现的问题的答案
那是因为我有
mycol.Item(20)
您正在引用的对象
(类为数据范围
)没有“默认”值
因此,您必须编写代码:
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
但是您必须将Set c=New DataRange
语句移动到For
循环中,如下所示:
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
循环之前实例化的相同数据范围
对象,从而使您拥有从上一个“数据”读取的相同应变
和应力
属性在I列和K列中绘制行,编辑以放大我在OP代码中找到的问题的答案
那是因为我有
mycol.Item(20)
您正在引用的对象
(类为数据范围
)没有“默认”值
因此,您必须编写代码:
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
但是您必须将Set c=New DataRange
语句移动到For
循环中,如下所示:
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
循环之前实例化的相同数据范围
对象,从而使所有收集项都具有从I列和K列的最后一个“数据”表行读取的相同应变
和应力
属性