Excel运行时错误91,没有对象变量

时间:2015-06-09 21:42:29

标签: excel vba excel-vba

我收到以下代码的 Run-time Error '91' Object Variable or With Block not Set

我很困惑,因为我没有使用任何对象变量(我不认为,我是VBA的新手)。调试突出显示第6行。

我的代码是:

Dim i As Integer
i = 1
Columns("A:A").Select
Selection.Find(What:="" & Cells(i, 19).Value, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Activate
MsgBox ActiveCell.Row

1 个答案:

答案 0 :(得分:0)

  

我收到了运行时错误' 91'对于以下代码,对象变量或未设置块。

使用.Find时,请检查是否返回了匹配项,如果找到则显示该行,否则您将收到上述错误。

试试这个

Option Explicit

Sub Sample()
    Dim i As Integer
    Dim aCell As Range
    Dim ws As Worksheet

    i = 1

    '~~> Replace this with the relevant sheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        Set aCell = .Columns(1).Find(What:=.Cells(i, 19).Value, _
                                     LookIn:=xlFormulas, _
                                     LookAt:=xlPart, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=False, _
                                     SearchFormat:=False)

        '~~> Check if the find returned a match
        If Not aCell Is Nothing Then
            MsgBox aCell.Row
        Else
            MsgBox "Not Found"
        End If
    End With
End Sub