通过Union创建的迭代与范围

时间:2017-11-17 15:01:27

标签: excel vba excel-vba

以下代码将工作表中创建的每个值超过10添加到" Over10"范围:

Sub IterateOver10()

Dim Over10 As Range

For Each cell In ActiveSheet.UsedRange.Cells
    If cell > 10 Then
        If Over10 Is Nothing then
            Set Over10 = cell
        Else
            Set Over10= Union(cell,Over10)
        End If
    End If
Next cell

我想遍历" Over10"中的每个项目。使用循环并检查它是否存在于另一个范围内。问题是以下迭代:

For each cell2 in Over10
    ' check if exists in another range
next cell2

不会为这样宣布的范围工作,因为它似乎使用了从cell2到(cell2 + Over10的数量)的范围。有关解决方法的任何建议。我应该使用数组吗?

谢谢, 巴特克

2 个答案:

答案 0 :(得分:0)

有很多方法可以做到这一点。其中一个是嵌套循环,您可以根据需要遍历两个集合(或范围或数组):

Sub IterateOver10()

    Dim myCell          As Range
    Dim Over10          As Range
    Dim myCollection    As New Collection
    Dim myCollection2   As New Collection

    Dim iterator        As Variant
    Dim iterator2       As Variant

    For Each myCell In ActiveSheet.UsedRange
        If myCell > 10 Then
            myCollection.Add (myCell)
        End If
    Next myCell

    myCollection2.Add 15
    myCollection2.Add 16

    For Each iterator2 In myCollection2
        For Each iterator In myCollection
            If iterator = iterator2 Then
                Debug.Print iterator
            End If
        Next iterator
    Next iterator2

End Sub

因此,如果您的输入在开头看起来像这样:

enter image description here

在您的名为myCollection的集合中,您将拥有12,13,14和15.然后在myCollection2中,您会发现15个集合中都有15个,它将打印在即时窗口中。

答案 1 :(得分:0)

感谢Vityata,我已经尝试了你的建议,并提出了以下代码来比较新创建的集合中的值与另一个工作簿的工作表名称,并隐藏那些未找到匹配项的工作表:

Sub Over10Vol2()

Dim myCell As Range
Dim Over10 As New Collection

For Each myCell In ActiveSheet.UsedRange
    If myCell > 10 Then
        Over10.Add (myCell)
    End If
Next myCell

Dim Final As Workbook
Set Final = Workbooks("testbook")

Dim ws As Worksheet
Dim cell2 As Variant

For Each ws In Final.Worksheets
    For Each cell2 In Over10 ' jumps from here...
        If ws.Name <> cell2 Then
            ws.Visible = False
        Else
            ws.Visible = True
        End If
    Next cell2
Next ws                       ' to here

End Sub

但这不起作用,因为代码完全忽略了第二个For Each循环中的If子句,它只是从“for each cell2 ...”直接跳到“next ws ”。 感谢您的任何建议