运行时错误“ 91”未设置对象变量或带块变量

问题描述

我有一个运行了一年多的Excel宏,直到昨天我遇到错误Run-time error '91'. Object variable or With block variable not set。我可以确认所有工作表都在。感谢任何建议进行故障排除。我突出显示了发生错误的那一行。

Sub Insert_Last_to_input()
    Dim dateBaltic As Date
    Dim rngFFA As Range
    Dim longLastRowNo As Long
    Dim longBaltic,longFEI,longMB As Long
    
    dateBaltic = Sheets("Input").Range("B2").Value
    
    Sheets("Baltic FFA").Select
    
    With ActiveSheet
        longLastRowNo = .Range("A:A").Find(What:=dateBaltic,LookIn:=xlValues).Row
        '**Error above:"Run-time error '91'. Object variable or With block variable not set"**
        Set rngFFA = .Range("B" & longLastRowNo & ":F" & longLastRowNo)
    End With
End Sub

解决方法

问题似乎是由于无法“查找”文本,因此无法将其行返回给您。 也就是说-在活动工作表列A中找不到“输入”工作表单元格“ B2”中的文本。

,

谢谢大家。我找到了答案,但确实很奇怪。

首先,问题出在“ .Find”。 Excel无法找到我想要的值,因为列宽太小并且无法显示全文!参见下图1。

Screenshot 1

在上面,longLastRowNo的正确值为213。所以我要做的是增加列宽,以便可以显示全文。参见下图2。

Screenshot 2

请注意,当我扩大列的宽度时,“。Find”能够找到正确的行号并将其分配给longLastRowNo,即213。

所以问题解决了。非常感谢大家!

,

查找问题的方法

您的问题似乎已经解决,但您必须深入了解问题的实质。您可以使用以下快速修复方法:

longLastRowNo = .Range("A:A").Find(What:=dateBaltic,LookIn:=xlFormulas).Row

但是我强烈建议您使用正确的方法,例如:

With WorkSheets("Baltic FFA")
    Dim cel As Range
    Set cel = .Range("A:A").Find(What:=dateBaltic,_
                                 LookIn:=xlFormulas,_
                                 LookAt:=xlWhole)
    If Not cel Is Nothing Then
    ' Cell found.
        longLastRowNo = cel.Row
        Set rngFFA = .Range("B" & longLastRowNo & ":F" & longLastRowNo)
    Else
    ' The cell could not be found.
        MsgBox "Could not find..."
        Exit Sub
    End With
End With

使行Sheets("Baltic FFA").Select多余(不需要)。

在此legendary post中了解如何避免使用Select