遍历 Excel VBA 中的范围时出现错误 91 和 424

Errors 91 and 424 when iterating over ranges in Excel VBA

我绝对是 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 行。我究竟做错了什么?我已经用谷歌搜索了一段时间,但我尝试过的所有解决方案都不起作用。

我认为错误是因为,如评论中所述,您的 "for each" 没有被正确使用。试试这个:

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 是什么,但这应该可以帮助您入门。我还将 "Dim cell" 更改为 "Dim cel" 因为 "cell" 也被 VBA

使用