清除查找/突出显示功能时的运行时错误91

时间:2014-01-13 15:30:33

标签: vba find runtime-error highlight

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

find函数运行正常,但我遇到的问题是当使用'ClearHighlight'时(在搜索之前)然后我得到运行时错误91 - '对象变量或使用块变量未设置'< / p>

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

1 个答案:

答案 0 :(得分:1)

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

Sub ClearHighlight()
   if FoundRange is nothing then exit sub

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