从集合中获取一行?

Get access to a row from the collection?

我正在尝试将我的工作表中的所有行添加到一个集合中,然后访问第一行的第一个单元格 - 我的集合的第一个元素的第一个单元格。但是当我 运行 我的宏时,我得到一个错误 - 需要 424 对象。我不明白,请问你有什么问题吗?

Sub test()
Dim collection1 As New Collection
For Each rw In Rows
If IsEmpty(rw.Cells(1).Value) = False Then
   collection1.Add (rw)
   End If
Next
Cells(1, 2) = collection1.Count - Works correct
Cells(1, 3) = collection1(1).Cells(1).Value
End Sub

需要使用rw变量的EntireRow属性赋值给集合:

collection1.Add (rw.EntireRow)

要么,要么只是从 Add 语句中删除括号:

collection1.Add rw

所以整个代码:

Sub test()
Dim collection1 As New Collection
For Each rw In Range("A1:A10").Rows
    If IsEmpty(rw.Cells(1).Value) = False Then collection1.Add (rw.EntireRow)
Next
Cells(1, 2) = collection1(1).Cells(1).Value
End Sub

方括号 正在评估 rw 对象(顺便说一句,它不是 Dimensioned),因此将它的值插入到集合中,而不是行中对象本身。


另请注意,我删除了 End If 语句,因为您只执行一个操作,所以很容易在一行中完成