以下代码将它在工作表中找到的每个超过 10 的值添加到“超过 10”范围:
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 的计数) 的范围。有关解决方法的任何建议。我应该使用数组吗?
谢谢,巴特克
有很多方法可以做到这一点。其中之一是嵌套循环,您可以在其中迭代两个集合(或范围或数组,如您所愿):
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
因此,如果您的输入在开始时如下所示:
在您命名的集合中,myCollection
您将有 12、13、14 和 15。然后在 15 中myCollection2
您会发现两个集合中都有 15,并且它将打印在直接窗口上。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句