VBA运行时错误91对象变量未设置

时间:2013-07-24 13:12:17

标签: excel vba excel-vba

我正在尝试选择仅具有今日日期的范围,但在Cells.find(TodayLast).Activate行上接收运行时错误91。我无法理解似乎是什么问题。

 Sub Escalation()

Dim rng As Range
Dim rngsend As Range
Dim OutApp As Object
Dim OutMail As Object
Dim cell As Range
Dim strto As String
Dim rngHeader As Range
Dim TodayFirst As Range
Dim TodayLast As Range
Dim LastDate As String

' Finds the area of today's range
LastRow = Sheets("Escal").Range("A65536").End(xlUp).Row
Cells(LastRow, 1).Activate
Set TodayLast = ActiveCell
Cells.find(TodayLast).Activate
Set TodayFirst = ActiveCell
Range(TodayFirst, TodayLast.Offset(0, 6)).Select

'Sorterar breacharna - Sorts the breaches
Selection.Sort Key1:=Range("G1"), Key2:=Range("B1"), Key3:=Range("D1")

'A loop that divides the various comps and enters a GoSub formula that prepares mails
Cells(TodayFirst.Row, 7).Activate
Set CompanyFirst = ActiveCell
Do Until IsEmpty(CompanyFirst)
Cells.find(What:=CompanyFirst, LookIn:=xlValues, SearchDirection:=xlPrevious).Activate
Set CompanyLast = ActiveCell
GoSub PrepareMail
Cells(CompanyLast.Row + 1, 7).Activate
Set CompanyFirst = ActiveCell

Loop

Cells(LastRow, 1).Select

Exit Sub

2 个答案:

答案 0 :(得分:0)

“Escal”可能不是活动表。在查找最后一行时,您完全限定范围,但不在任何后续代码中。您还有一堆不必要的激活和选择,这导致您正在经历的那种错误。声明对象变量并使用它们。您将失去确保正确对象处于活动状态的开销,并避免将来出现此类错误。

您还应该总是要求变量声明。 (工具 - >选项...)

尝试重写这样的代码:

Sub AvoidRTE91()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim todayLast As Range
    Dim todayFirst As Range
    Dim todayRange As Range

    Set ws = ThisWorkbook.Sheets("Escal")
    lastRow = ws.Range("A65536").End(xlUp).Row

    ' added message for debugging purposes. Remove once you figure out what is wrong.
    MsgBox ws.Cells(lastRow, 1) & " is in cell " & ws.Cells(lastRow, 1).Address
    Set todayLast = ws.Cells(lastRow, 1)
    Set todayFirst = ws.Cells.Find(todayLast)
    ' you don't have to select the range to work with it
    Set todayRange = ws.Range(todayFirst, todayLast.Offset(0, 6))
    ' now instead of using selection, use todayRange...

End Sub

答案 1 :(得分:0)

在这一行:

Cells.find(What:=CompanyFirst, LookIn:=xlValues, SearchDirection:=xlPrevious).Activate

您设置了whatlookinsearchdirection。然后,如果再次执行例程,则在此行中第一次调用find:

Cells.find(TodayLast).Activate

失败,因为您尝试使用之前定义的whatlookinsearchdirection

这就是为什么它只在你第一次执行时才能正常工作。

(感谢您的问题,我解决了我的问题:))