在 Collection 中打印条目

Printing entries in a Collection

我有一个 Collection 包含 x 件物品。我只需要将 Collection 的内容输出到 Excel 列。

For Each item In myCollection
'Insert code here

Next item  

知道我该怎么做吗?

您可以将起始行或列从 1 更改为您想要的任何值。您也可以通过将 'r = r + 1' 替换为 'c = c + 1' 来增加列来插入单元格。

注意:将 "Sheet1" 更改为您的工作表名称,这只是我使用的默认名称,因为我不知道您实际工作表的名称。

Dim r As Integer
Dim c As Integer
r = 1 'Row 1
c = 1 'Column A
For Each item In myCollection
    ThisWorkbook.Worksheets("Sheet1").Cells(r, c).Value = item
    'Increment Row by 1
    r = r + 1
Next item

这是 Dictionary 对象优于 Collection 对象的原因之一。

对于集合,您必须遍历整个集合对象以检索所有值。

使用字典,您可以一次检索所有值,这在写入工作表时速度非常快。一次写入一个单元格是您在 Excel.

中可以做的最低效的事情之一

所以这里是如何转换为使用字典。注意最后一行。整个字典一次性写入范围:

Sub zaanwar()

    Dim myDictionary As Object

    Set myDictionary = CreateObject("scripting.dictionary")

    With myDictionary
        .Item("key1") = "val1"
        .Item("key2") = "val2"
        .Item("key3") = "val3"
        .Item("key4") = "val4"
    End With

    [a1:d4] = Application.Transpose(myDictionary.Items)

End Sub