VBA Excel错误对象变量或未设置块变量

时间:2013-07-02 15:44:47

标签: excel vba excel-vba excel-2010

下面的代码会找到相邻的单词,但如果电子表格中没有单词,我会尝试添加错误处理程序。我正在获取错误对象变量或未设置块变量。问题是什么?或者你可以帮助修复错误信息,以便如果找不到单词,msgbox会显示MsgBox“抱歉找不到文本,请再试一次。宏停止”。谢谢!

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

1 个答案:

答案 0 :(得分: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