将一系列单元格添加到集合中,然后调用集合中的每个项目以在excel

时间:2016-12-07 10:49:45

标签: excel vba excel-vba collections

我正在尝试在VBA中添加一系列单元格,然后使用集合中的每个项目来执行我的工作。我设法将数据存储到集合中,但无法通过使用Collection.Item和debug.Print将其显示在立即窗口上来调用它。但是,如果我只将一个单元格存储到集合中,这是有效的。这是我的VBA代码:

lastRowIndex = Cells(Rows.Count, 1).End(xlUp).Row
Set PGname = New Collection
Set HScode = New Collection
For i = 1 To lastRowIndex
    PGname.Add Range((Cells(i, 1)), (Cells(i, 2)))
    HScode.Add (Cells(i, 2))
Next i
Debug.Print PGname.Item(1)  'this is not work
Debug.Print HScode.Item(1) 'this is work

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

试试这个:

Option Explicit

Public Sub Test()
    Dim i                   As Long
    Dim lastRowIndex        As Long
    Dim PGname              As Object
    Dim HScode              As Object

    lastRowIndex = 10

    Set PGname = New Collection
    Set HScode = New Collection
    For i = 1 To lastRowIndex
        PGname.Add Range((Cells(i, 1)), (Cells(i, 2)))
        HScode.Add (Cells(i, 2))
    Next i
    Debug.Print PGname.Item(1).Address
    Debug.Print PGname.Item(1)(1)(1) 'this would print you cell A1

End Sub

您收到错误,因为您尝试打印多个单元格的范围。 看看这两个debug.prints。在A1中加入一些值以确定它打印的内容。