【问题标题】:Run-time error '91'. Object variable or With block variable not set运行时错误“91”。未设置对象变量或 With 块变量
【发布时间】:2026-01-05 01:00:01
【问题描述】:

我有一个 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

【问题讨论】:

  • 你需要检查.Find是否返回了一些东西。 Here 就是一个例子。查看该链接中的 第 1 节 If Not aCell Is Nothing Then 顺便说一句,此类问题在 * 中已被问过无数次。
  • 在一行中声明多个变量,例如输入Long 是这样完成的:Dim longBaltic As Long, longFEI As Long, longMB As Long。在您的代码中,前两个声明为Variant

标签: excel vba excel-2010


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

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

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

    这样问题就解决了。非常感谢大家!

    【讨论】:

      【解决方案3】:

      在麻烦中寻找方法

      您的问题似乎已经解决了,但在内心深处,您必须知道事实并非如此。您可以使用以下快速修复:

      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

      【讨论】: