【问题标题】:run-time error 91 when clearing a find/highlight function清除查找/突出显示功能时出现运行时错误 91
【发布时间】:2014-02-01 10:09:01
【问题描述】:

我正在运行以下宏以通过 MS XL 2003 中的数据库执行基本的“FindHighlight”功能

查找功能完美运行,但我遇到的问题是,当使用“ClearHighlight”时(在进行搜索之前),我得到运行时错误 91 -“对象变量或未设置块变量”

我知道在使用此功能之前我需要完成搜索,但使用该工具的其他人可能不需要 - 我想知道是否有办法防止出现此警报? (VBA 初学者!!)

谢谢!

Dim FoundRange As Range

Sub FindHighlight()
Dim tempCell As Range, Found As Range, sTxt As String
sTxt = InputBox("Search string")
If sTxt = "False" Then Exit Sub
Set Found = Range("A1")
Set tempCell = Cells.Find(what:=sTxt, After:=Found, SearchDirection:=xlNext, MatchCase:=False)
If tempCell Is Nothing Then
MsgBox prompt:="Not found", Title:="Finder"
Exit Sub
Else
Set Found = tempCell
Set FoundRange = Found
End If
Do
Set tempCell = Cells.FindNext(After:=Found)
If Found.Row >= tempCell.Row And Found.Column >= tempCell.Column Then Exit Do
Set Found = tempCell
Set FoundRange = Application.Union(FoundRange, Found)
Loop
FoundRange.Interior.ColorIndex = 6
FoundRange.Font.ColorIndex = 3
End Sub

Sub ClearHighlight()
FoundRange.Interior.ColorIndex = xlNone
FoundRange.Font.ColorIndex = xlAutomatic
End Sub

【问题讨论】:

    标签: vba find runtime-error highlight


    【解决方案1】:

    如果 FoundRange 未设置,则其值为 Nothing 所以:

    Sub ClearHighlight()
       if FoundRange is nothing then exit sub
    
       FoundRange.Interior.ColorIndex = xlNone
       FoundRange.Font.ColorIndex = xlAutomatic
    End Sub
    

    【讨论】:

    • 也许只需在 OP 中添加 MsgBox 即可:If tempCell Is Nothing Then MsgBox ...
    • 非常感谢 - 非常感谢!
    猜你喜欢
    • 2019-11-26
    • 1970-01-01
    • 1970-01-01
    • 2020-12-01
    • 2016-11-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-09
    相关资源
    最近更新 更多