我有两个名为FindTempRow
和FindBatchRow
Sub FindTempRow()
With Worksheets("TEMPLATES").Range("G:G")
Set t = .Find("Template", LookIn:=xlValues)
If Not t Is Nothing Then
FirstAddress1 = t.Address
Do
Call FindBatchRow
Set t = .FindNext(t)
Loop While Not t Is Nothing And t.Address <> FirstAddress1
End If
End With
End Sub
Sub FindBatchRow()
With Worksheets("DISTRIBUTION LIST").Range("C:C")
Set d = .Find(BatchNo, LookIn:=xlValues)
If Not d Is Nothing Then
FirstAddress2 = d.Address
Do
Set d = .FindNext(d)
Loop While Not d Is Nothing And d.Address <> FirstAddress2
End If
End With
End Sub
FindTempRow 在 Do While循环中调用 FindBatchRow 。
问题是每当我运行代码时它都会给我一个错误:Runtime Error Code (91) Object Variable or With Block variable not set
提供错误的代码位于 FindTempRow :
Loop While Not t Is Nothing And t.Address <> FirstAddress1
我尝试删除call FindBatchRow
中的Sub FindTempRow
,但运行正常。在sub FindBatchRow
解决方案: by @Rory
来自 Sub FindBatchRow 的 REPLACE: Set t = .FindNext(t)
WITH: Set t = .Find("Template", After:=t, LookIn:=xlValues)
答案 0 :(得分:2)
在循环的第一次运行中,如果没有找到任何内容,那么当你的代码试图从Upstream
获取地址时实际上什么都没有,它会抛出错误。从循环t
中删除此部分。而是使用If语句在do循环内检查此条件,并使用And t.Address <> FirstAddress1
答案 1 :(得分:0)
VBA总是解析if子句中的所有部分(或者在while子句中),所以如果你在使用和运算符并且第一个是假的,那么第二个会被检查,如果t什么都不是,那就失败了。做这样的事情:
Do
Call FindBatchRow
Set t = .FindNext(t)
Dim a As boolean
a = False
If Not t is Nothing
If t.Address <> FirstAddress1
a = True
End If
End If
Loop While a
相应地应该在你的FindBatchRow中完成同样的事情。