Excel VBA:如何解决运行时错误"91"?

问题描述:

我得到了错误:

Run-time error '91': Object variable or With block variable not set

当我尝试执行此代码时:

when I try to execute this code:

MsgBox Worksheets("Sheet2").Range("2:2").Find(Worksheets("Sheet1").Range("E5").Value, , , xlWhole)

为什么?这行怎么了?

编辑

如果我正在管理文本或数字,则该代码有效.但是我有一个问题,我在Worksheets("Sheet1").Range("E5")Worksheets("Sheet2").Range("2:2")上有日期.

The code works if I am managing text or numbers. But I have that issue what I have dates on Worksheets("Sheet1").Range("E5") and Worksheets("Sheet2").Range("2:2").

result分配给范围,并使用.Find()设置范围. 如果未找到任何内容,则Range()将为Nothing:

Assign the result to a Range and use the .Find() to set the range. If nothing is found, then the Range() would be Nothing:

Sub TestMe()

    Dim result As Range

    With Worksheets(1)
        Set result = .Range("2:2").Find("Something", LookAt:=xlWhole)
    End With

    If Not result Is Nothing Then
        Debug.Print result.Address
    Else
        Debug.Print "Something is not on the second row!"
    End If

End Sub

如果使用日期,则必须使用LookAt:=xlWhole参数:

The LookAt:=xlWhole argument is a must, if one is working with dates:

Excel .范围.查找文档