Errors 91 and 424 when iterating over ranges in Excel VBA

81 Views Asked by At

I am an absolute VBA beginner. I have been trying to create a function that separates a large range into smaller ranges. However, when I try and iterate over the large range, I get errors 91 and 424 interchangeably. Here is the relevant bit of code:

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 is a range, defined as such:

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

Next i

What I'm trying to do here is group together non-zero cells that have been entered in a grid. I am considering cells as part of a group if the cell is adjacent to another non-zero cell.

The error occurs with the For Each line highlighted. What am I doing wrong? I've been googling this for a while and all the solutions I've tried don't work.

1

There are 1 best solutions below

1
On BEST ANSWER

I think the error is because, as mentioned in the comments, that your "for each" isn't being used correctly. Try this:

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

I don't think that'll work straight off the bat, because I don't know what your UDFs are, but that should get you started. I also changed "Dim cell" to "Dim cel" since "cell" is also used by VBA