Vba 清除查找/突出显示函数时出现运行时错误91

Vba 清除查找/突出显示函数时出现运行时错误91,vba,find,runtime-error,highlight,Vba,Find,Runtime Error,Highlight,我正在运行以下宏,通过MS XL 2003中的数据库执行基本的“FindHighlight”功能 find函数工作得很好,但我遇到的问题是,当使用“ClearHighlight”(在进行搜索之前)时,我会得到运行时错误91-“Object variable或With block variable not set” 我知道我需要在使用此功能之前完成搜索,但其他使用此工具的人可能不会-我想知道是否有办法防止出现此警报? (VBA初学者!!) 谢谢大家! Dim FoundRange As Range

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

find函数工作得很好,但我遇到的问题是,当使用“ClearHighlight”(在进行搜索之前)时,我会得到运行时错误91-“Object variable或With block variable not set”

我知道我需要在使用此功能之前完成搜索,但其他使用此工具的人可能不会-我想知道是否有办法防止出现此警报? (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

如果未设置
FoundRange
,则其值为
Nothing
,因此:

Sub ClearHighlight()
   if FoundRange is nothing then exit sub

   FoundRange.Interior.ColorIndex = xlNone
   FoundRange.Font.ColorIndex = xlAutomatic
End Sub

也许只需添加一个
MsgBox
就像在OP:
中那样:如果tempCell什么都不是,那么MsgBox…
非常感谢-非常感谢!