D. R. M. Smith
D. R. M. Smith

Reputation: 5

Loop run-time error 91

I have created a loop in MS excel which is supposed to go down row-by-row, look into another sheet and compare a value. If the value is different in the second sheet, the first sheet is updated and a few formats are changed. This loop spans ~50 rows, but excludes a couple via use of Select Case. It runs fine until the 26th loop where I get a

run-time error 91

I've read the Microsoft definition of this error (and searched stackoverflow) but no joy thus far.

Fails on line beginning If Range(G:G).Find... where i = 26

Dim wb As Workbook
Dim wbData As Workbook
Dim i As Integer
Dim PIN As String
Dim status As String

Application.ScreenUpdating = False

Set wb = ThisWorkbook
Sheet4.Select

Set wbData = Workbooks.Open("C:\test.xlsx", , 1)

For i = 3 To 56
    Select Case i
    Case 23, 24, 40, 41
        'do nothing
    Case Else
        wb.Activate
        PIN = Sheet4.Cells(i, 7)
        If PIN <> "" Then
            wbData.Activate
            If Range("G:G").Find(What:=PIN, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=True) Then
                status = Cells(Range("G:G").Find(What:=PIN, LookIn:=xlFormulas, LookAt:=xlWhole, MatchCase:=True).row, 33)
                wb.Activate
                If status <> Cells(i, 33) Then
                    'Updates with new status
                    Cells(i, 33) = status
                    With Range(Cells(i, 1), Cells(i, 38)).Interior
                        'change a few bits
                    End With
                End If
            End If
        End If
    End Select
Next i

Upvotes: 0

Views: 442

Answers (1)

Miguel_Ryu
Miguel_Ryu

Reputation: 1418

Try the below:

If Not Range("G:G").Find(What:=PIN, LookIn:=xlFormulas, LookAt:=xlWhole, _
    MatchCase:=True) Is Nothing Then

The default value for an object that doesn't exist is Nothing hence giving:

Error 91 - “Object variable set to nothing”`

Upvotes: 4

Related Questions