循环运行时错误91

时间:2018-01-25 14:01:52

标签: excel vba excel-vba runtime-error

我在MS excel中创建了一个循环,它应该逐行下去,查看另一个工作表并比较一个值。如果第二张表中的值不同,则更新第一张表并更改几种格式。这个循环跨越约50行,但通过使用Select Case排除了一对。它运行良好,直到我得到

的第26个循环
  

运行时错误91

我已经阅读了Microsoft对此错误的定义(并搜索了stackoverflow),但到目前为止还没有任何乐趣。

If Range(G:G).Find...开始失败,其中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

1 个答案:

答案 0 :(得分:4)

尝试以下方法:

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

不存在的对象的默认值为Nothing,因此给出:

  

错误91 - “对象变量设置为空”`

相关问题