You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA搜索隐藏工作表报错Runtime Error 91:对象变量未设置

VBA代码Runtime Error 91错误排查与修复

核心错误原因

你的代码触发Error 91的直接原因是对象变量赋值未使用Set关键字。VBA中,Range这类对象类型的变量必须通过Set来赋值,而你直接用foundCell1 = ws.Range("I:I").Find(...),导致对象变量未被正确初始化,因此报错。

其他逻辑问题及修复

除了核心赋值错误,代码还有几处逻辑问题需要修正:

  1. 搜索结果判断逻辑颠倒:原代码If Not foundCell1 Is Nothing Or foundCell2 Is Nothing的逻辑是“foundCell1存在 或者 foundCell2不存在”,完全不符合你“任一搜索结果存在就处理”的需求,应改为If Not foundCell1 Is Nothing Or Not foundCell2 Is Nothing。
  2. 未找到提示的位置错误:原代码把提示框放在循环内部,会导致每遍历一个无匹配的工作表就弹出提示,正确的做法是在循环结束后,判断整个搜索过程是否无任何匹配再弹出提示。
  3. 可见性变量类型优化:原代码用Boolean存储工作表可见性,建议改用XlSheetVisibility枚举类型,避免处理极隐藏(xlSheetVeryHidden)工作表时出现异常。

修正后的完整代码

Private Sub TextBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = vbKeyReturn Then
        SearchSheets
    End If
End Sub

Sub SearchSheets()
    Dim ws As Worksheet
    Dim searchTerm As String
    Dim foundCell1 As Range
    Dim foundCell2 As Range
    Dim OrVis As XlSheetVisibility
    Dim isFound As Boolean

    searchTerm = Trim(TextBox1.Text)
    isFound = False

    For Each ws In ThisWorkbook.Worksheets
        If InStr(1, ws.Name, "-") > 0 And Not Right(ws.Name, 3) = "MAP" Then
            OrVis = ws.Visible
            ws.Visible = xlSheetVisible

            ' 修复:添加Set关键字赋值对象变量
            Set foundCell1 = ws.Range("I:I").Find(searchTerm, LookIn:=xlValues, LookAt:=xlWhole, _
                SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
            Set foundCell2 = ws.Range("K:K").Find(searchTerm, LookIn:=xlValues, LookAt:=xlPart, _
                SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)

            ' 修复:正确判断任一搜索结果存在
            If Not foundCell1 Is Nothing Or Not foundCell2 Is Nothing Then
                ws.Activate
                ws.Move After:=Worksheets("Index")
                If Not foundCell1 Is Nothing Then
                    foundCell1.Select
                Else
                    foundCell2.Select
                End If
                isFound = True
                Exit For
            End If

            ws.Visible = OrVis
        End If
    Next ws

    ' 循环结束后统一提示无结果
    If Not isFound Then
        MsgBox "Not Found", vbInformation, "Search Results"
    End If
End Sub

额外排查建议

  • 确认搜索规则:LookAt:=xlWhole是精确匹配整单元格内容,xlPart是模糊匹配单元格内的子字符串,确保搜索规则符合你的需求。
  • 检查工作表状态:如果目标工作表被保护,Find方法可能无法正常执行,需要先解除保护(若业务允许)。
  • 优化搜索范围:避免搜索整列(Range("I:I")),改用已使用的单元格范围,比如ws.Range("I1:I" & ws.Cells(ws.Rows.Count, "I").End(xlUp).Row),提升搜索效率。

内容的提问来源于stack exchange,提问作者tome10

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 03:46:03