VBA Excel 错误对象变量或未设置块变量
Posted
技术标签:
【中文标题】VBA Excel 错误对象变量或未设置块变量【英文标题】:VBA Excel error object variable or with block variable not set 【发布时间】:2013-07-02 15:44:47 【问题描述】:下面的代码将找到相邻的单词,但如果电子表格中没有单词,我尝试添加错误处理程序。我收到错误对象变量或未设置块变量。问题是什么?或者您可以帮助修复错误消息,以便如果找不到该单词,则 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
【问题讨论】:
你需要if not match is nothing
行之前findOffset = match.Offset(, 1).Value
行
@JosieP 是正确的。 match Is Nothing
时出现您的错误。
是的,我试过了,但仍然报错
在你使用它之后 不是很好的测试匹配 ;-)
【参考方案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
【讨论】:
以上是关于VBA Excel 错误对象变量或未设置块变量的主要内容,如果未能解决你的问题,请参考以下文章