2014-01-13 30 views
0

當我運行下面的宏通過MS XL 2003運行時錯誤91清除查找/高亮功能

查找功能完美的作品數據庫來執行基本「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 

回答

1

如果FoundRange沒有設置它的值是Nothing這樣:

Sub ClearHighlight() 
    if FoundRange is nothing then exit sub 

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

也許只是添加一個'MsgBox'像OP:'如果tempCell是Nothing然後 MSGBOX ...' –

+0

謝謝非常感謝 - 非常感謝! – user3190728