Search code examples
excelvbaforeachruntime-error

How to Fix a Run-Time Error While Using For Each Loop


I have a code in which I am looping through a range of cells and comparing it to an input box entry. If the cell does not match the entry the code does nothing, if the code does match the entry it clears the contents of the cell. Most of the code has worked fine. The loop variable is correctly showing the value of each cell that it should loop through when monitoring it in breakout mode, and it is successfully comparing it to the input text.

        UPC = InputBox("UPC #?")
        For Each b In SRange
            If CStr(b) = CStr(UPC) Then
                b.ClearContents
            End If
        Next

The issue that I am running into is that as soon as it finds a match and moves on to the line where it is supposed to do something ( b.ClearContents) It throws a Run-Time Error 424 Object Required fault.

I have tried using several different operations such as b.Address and b.Value, but they all give the same fault. Strangely enough, if I MsgBox(b) it works just fine and shows me the value of the cell.


Solution

  • This code tested working:

    
    Sub so75513894ObjectError()
      Dim SRange As Object
      Dim UPC As String
      'Dim aRange
      
      Dim b
           
      Set SRange = ActiveSheet.Range("A1:B5")
      'aRange = ActiveSheet.Range("A1:B5").Value
      
       UPC = InputBox("UPC #?")
       For Each b In SRange
         If CStr(b) = CStr(UPC) Then
            b.ClearContents
         End If
       Next
    
    End Sub
    
    Private Sub CommandButton1_Click()
       so75513894ObjectError
    End Sub