我正在尝试迭代范围内的每个单元格。过去,我可以使用以下方法完成此操作:
Function iterateOverEverything(someRange) As Integer
Dim cell As range
For Each cell In someRange
doSomething(cell)
Next
iterateOverEverything = 3
End Function
以上代码有效。
问题是我正在尝试创建一个给定多个范围的函数,并分别迭代它们 - 我不想将范围联合起来,我必须能够比较多个范围。我目前的策略是使用范围数组,然后for each
范围内的每个单元格。请考虑以下代码:
Function iterateOverMultipleRanges(rangeZero, rangeOne) As Integer
Dim ranges(1) As range
ranges(0) = rangeZero
ranges(1) = rangeOne
Dim cell As range
For i = 0 To UBound(ranges) - 1
For Each cell In ranges(i)
doSomething(cell)
Next
Next
iterateOverMultipleRanges = 3
End Function
以上代码无法正常工作。
我相信我已经确定了问题:由于某种原因,for each
无法迭代数组的内容。要遇到此问题,请尝试运行以下代码:
Function iterateOverMultipleRanges(rangeZero, rangeOne) As Integer
Dim ranges(1) As range
ranges(0) = rangeZero
ranges(1) = rangeOne
Dim cell As range
For Each cell In ranges(1)
doSomething(cell)
Next
iterateOverMultipleRanges = 3
End Function
上面会抛出错误。
我应该如何迭代多个范围?我错过了什么?
请注意,我无法找到任何相同的问题,但由于我对该问题缺乏了解,完全有可能这与其他问题密切相关。
谢谢!
编辑:有关答案的其他信息,请参阅mwolfe02的答案:https://stackoverflow.com/a/5042718/8133062
属性集用于对象(例如,类实例),
属性设为“普通”数据类型(例如,字符串,布尔值,长整数等)
答案 0 :(得分:2)
分配对象时需要使用Set
:
Function iterateOverMultipleRanges(rangeZero As Range, _
rangeOne As Range) As Integer
Dim ranges(1) As range
Set ranges(0) = rangeZero
Set ranges(1) = rangeOne
Dim cell As range
For i = 0 To UBound(ranges) - 1
For Each cell In ranges(i)
doSomething(cell)
Next
Next
iterateOverMultipleRanges = 3
End Function