我有一个表格,想要将其中每一行转换成一个对象。该对象将会拥有每一列的属性。
我写了这个函数:
Public Function GetProducts() As Object
Set GetProducts = New Collection
Dim p As New ProductInfo
Dim rng As Range
Dim xRow As Range
Set rng = Sheet2.Range("A2:I" & Sheet2.Range("A2").End(xlDown).Row)
For Each xRow In rng.Rows
p.Id = xRow.Cells(1, 1).Value
p.Cod = xRow.Cells(1, 2).Value
p.Name = xRow.Cells(1, 3).Value
p.productType = xRow.Cells(1, 4).Value
p.norma = xRow.Cells(1, 5).Value
p.masina = xRow.Cells(1, 6).Value
p.masinaType = xRow.Cells(1, 7).Value
p.operatori = xRow.Cells(1, 8).Value
p.sectie = xRow.Cells(1, 9).Value
GetProducts.Add Item:=p, Key:=CStr(p.Id)
Next xRow
End Function
我尝试使用以下子程序检查该功能:
Public Sub CheckProducts()
Dim products As Collection
Dim p As ProductInfo
Set products = GetProducts()
For Each p In products
MsgBox p.Id
Next p
End Sub
消息框总是返回20(我有20个项目在我的表中,最后一个ID是20)。
当我检查集合中的项目数量时,我得到了20,正如我所期望的那样。
有人能帮我理解为什么我无法迭代集合并获取每个项目的ID吗?