【问题标题】:How to call each item of a collection如何调用集合的每个项目
【发布时间】:2016-12-07 10:49:44
【问题描述】:

我设法将一系列单元格存储到一个集合中。

我正在尝试使用集合中的每个项目。

我未能通过使用Collection.Itemdebug.Print 在即时窗口中显示它来调用它。

如果我只将一个单元格存储到集合中,这将有效。

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 does not work
Debug.Print HScode.Item(1)  'this works

【问题讨论】:

  • 为什么你尝试debug.print一个范围对象通常会发生什么?
  • @CallumDA33 这是运行时错误'13':类型不匹配。

标签: vba excel collections


【解决方案1】:

试试这个:

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 中添加一些值以确保它打印的内容。

【讨论】:

  • 是的,我要做的是在集合存储后将至少 2 个单元格的范围打印到另一个单元格中。因为我想对集合中的数据做点什么。你的代码只是打印单元格 A1 所以这不是我需要的。你还有别的想法吗?感谢您的帮助。
  • 你能举个例子吗?有一些预期的输入和输出?
猜你喜欢
  • 1970-01-01
  • 2013-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多