从VBA中的集合中删除项目

时间:2013-09-03 10:20:31

标签: vba

我想删除collA(1)(9,0),collA(1)(9,1),collA(1)(9,2),collA(1)(9,3),collA(1 )(9,4),collA(1)(9,5)和collA(1)(9,6)。

下面的Sub Test()中的remove语句不起作用。

如何解决这个问题?

Sub Test()

    Dim A() As Integer
    Redim A(0 To 367907, 0 To  6) As Integer

    Dim i As Long
    Dim j As Integer

    For i = 0 To 367907
    For j = 0 To 6    
        A(i, j) = Worksheets("Sheet1").Cells(i + 1, j + 1)
    Next j
    Next i

    Dim collA As VBA.Collection

    Set collA = New Collection
    collA.Add A

    Erase A

    collA(1).Remove 10     '<--- This doesn't work

End Sub

1 个答案:

答案 0 :(得分:2)

您不需要数组,可以直接将值添加到集合对象中。这就是它的原因:))

如果你想要从集合中删除单元格D2,你必须知道它的索引

所以像这样设置你的表格

enter image description here

然后注意

您的收藏从1号开始,添加的第一个项目是单元格A1,然后是第二个单元格B1

因此您的索引10是单元格D2

使用以下代码从集合中删除D2

Sub Test()

    Dim c As Collection
    Set c = New Collection

    Dim i As Long, j As Long

    For i = 1 To Range("A" & Rows.Count).End(xlUp).Row
        For j = 1 To 6
            c.Add Cells(i, j)
        Next j
    Next i

    For i = 1 To c.Count
        Debug.Print c.Item(i), "count: " & i, "total items: " & c.Count
    Next i

    c.Remove 10
    Debug.Print vbCrLf

    For i = 1 To c.Count
        Debug.Print c.Item(i), "count: " & i, "total items: " & c.Count
    Next i

End Sub

导致立即窗口 CTRL + G

enter image description here