迭代Excel VBA中的范围时出现错误91和424

时间:2015-06-15 16:26:21

标签: excel vba excel-vba range

我是绝对的VBA初学者。我一直在尝试创建一个将大范围分成更小范围的函数。但是,当我尝试迭代大范围时,我可以互换地得到错误91和424。以下是相关的代码:

Dim cell As Range
Set cell = Range(Cells(1, 1), Cells(1, 1))
For Each cell In nonZeroes
    question = isTouching(cell, firstfeat)
    If question = True Then
        Set firstfeat = Union(firstfeat, cell)
        cell.Interior.ColorIndex = 3
    End If
Next

nonZeroes是一个范围,定义如下:

Dim nonZeroes As Range
For i = 3 To 87
For j = 3 To 87
    If Cells(i, j).Value = 0 Then
    End If
    If Cells(i, j).Value <> 0 Then
        If Not nonZeroes Is Nothing Then
            Set nonZeroes = Union(nonZeroes, Cells(i, j))
        Else
            Set nonZeroes = Cells(i, j)
        End If
    End If
Next j

接下来我

我在这里要做的是将已输入网格的非零单元组合在一起。如果细胞与另一个非零细胞相邻,我正在将细胞视为一组的一部分。

突出显示For Each行时出错。我究竟做错了什么?我已经谷歌搜索了一段时间,我尝试过的所有解决方案都不起作用。

1 个答案:

答案 0 :(得分:0)

我认为错误是因为,正如评论中所提到的那样,你的&#34;对于每个&#34;没有被正确使用。试试这个:

Dim cel
Set nonZeroes = Range(Cells(1, 1), Cells(10, 1)) ' You need to set the range to search through here.
For Each cel In nonZeroes
    question = isTouching(cel.Value, firstfeat)
    If question = True Then
        Set firstfeat = Union(firstfeat, cel.Value)
        cell.Interior.ColorIndex = 3
    End If
Next

我不认为它会直接发挥作用,因为我不知道你的UDF是什么,但这应该让你开始。我也改变了#34; Dim cell&#34;到了&#34; Dim cel&#34;因为&#34; cell&#34;也被VBA使用