2013-07-02 180 views
1

下面的代码将找到相邻的单词,但如果单词不在电子表格中,我尝试添加错误处理程序。我收到错误对象变量或未设置块变量。问题是什么?或者您可以帮助修复错误信息,以便如果未找到该单词,则msgbox将显示MsgBox“对不起,未找到文本,请重试,宏停止”。谢谢!VBA Excel错误对象变量或块变量未设置

Sub Module6() 
' 
'FindPlusOffset&Count 
' 
' 
Dim ws As Worksheet 
Dim match As Range 
Dim findMe As String 
Dim findOffset As String 
Dim Number As Long 

Set ws = ThisWorkbook.Sheets("Sheet1") 
findMe = "report" 'word not in spreadsheet 
Set match = ws.Cells.Find(findMe) 
findOffset = match.Offset(, 1).Value 'error occurs object variable or with block variable not set on this line 
Number = Evaluate("=SUMPRODUCT(--(NOT(ISERROR(FIND(""" & findMe & """,A1:AZ96,1)))))") 

If (Not match Is Nothing) Then 

    MsgBox "The adjacent word to """ & findMe & """ is """ & findOffset & """. It is found "" " & Number & """ times!" 

Else 
    'not match 
    MsgBox "Sorry the text was not found please try again. Macro stopping" 

End If 

End Sub 
+2

你所需要的',如果不匹配是前'findOffset = match.Offset nothing'线(1 ).Value'行 – JosieP

+0

@JosieP是正确的。当'match Is Nothing'时你的错误结果。 –

+0

是的,我试过,但仍然给出了错误 – mgrobins

回答

1

正如JosieP说,此代码按预期工作(我只是尝试了)

Sub Module6() 
' 
'FindPlusOffset&Count 
' 
' 
Dim ws As Worksheet 
Dim match As Range 
Dim findMe As String 
Dim findOffset As String 
Dim Number As Long 

Set ws = ThisWorkbook.Sheets("Sheet1") 
findMe = "report" 'word not in spreadsheet 
Set match = ws.Cells.Find(findMe) 

If (Not match Is Nothing) Then 

    findOffset = match.Offset(, 1).Value 'error occurs object variable or with block variable not set on this line 
    Number = Evaluate("=SUMPRODUCT(--(NOT(ISERROR(FIND(""" & findMe & """,A1:AZ96,1)))))") 
    MsgBox "The adjacent word to """ & findMe & """ is """ & findOffset & """. It is found "" " & Number & """ times!" 

Else 
    'not match 
    MsgBox "Sorry the text was not found please try again. Macro stopping" 

End If 

End Sub 
+0

谢谢你的工作太棒了! – mgrobins

相关问题