繁体   English   中英

未使用Excel-VBA设置对象变量或带块变量

[英]Object Variable or With Block variable not set using Excel-VBA

我有两个名为FindTempRowFindBatchRow潜艇

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

FindTempRowDo 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

我试着删除Sub FindTempRow call FindBatchRow ,它运行正常。 似乎每当在sub FindBatchRow调用另一个find方法时,我的代码就会忘记t地址

解决方案: @Rory

替换:子FindBatchRow Set t = .FindNext(t)

WITH: Set t = .Find("Template", After:=t, LookIn:=xlValues)

在循环的第一次运行中,如果什么都没找到,那么当您的代码尝试从实际上没有任何内容的t获取地址时,它将引发错误。 从循环And t.Address <> FirstAddress1删除此部分。 而是使用If语句在do循环中检查此条件,并在使用true退出true时从循环中ExitDo

VBA始终解析if子句(或while子句中)的所有部分,因此,如果在with中使用and运算符,而第一个为false,则第二个将被检查,如果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中执行相同的操作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM