2016-11-13 74 views
0

我在Excel VBA(使用Excel 2010)中具有以下代码,以欧洲格式(dd/mm/yyyy)查找特定日期,然后取消细胞(用它在该日期)下面的行:运行时错误消息91(对象变量未设置)

Sub Macro1() 

' Macro1 
Dim A As Variant 

' Input box to insert a date 
A = InputBox("Insert date of the last entry with format dd/mm/yyyy", "User date", Format(Now(), "dd/mm/yyyy")) 
If IsDate(A) Then 
    A = Format(CDate(A), "dd/mm/yyyy") 
Else 
    MsgBox "Date in the wrong format!" 
End If 

'Find the date above, in the variable A, in the Excel sheet 
Cells.Find(What:=A, After:=ActiveCell, LookIn:=xlFormulas, _ 
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False).Activate 

Range(Selection, Selection.End(xlDown)).Select 
Range(Selection, Selection.End(xlToRight)).Select 
Selection.EntireRow.Delete 

End Sub 

然而,当我运行宏,我得到的运行时错误消息91

对象变量未设置。

非常感谢您的帮助。

+2

如果搜索范围包含实际日期(不是文本),那么您需要使用日期搜索,而不是字符串表示。 'Cells.Find(What:= CDate(A),' –

回答

0

出现此错误是因为Find方法未返回任何结果,但您尝试在同一行中激活此不存在的范围。

Option Explicit 

Sub Macro1() 

Dim A As Variant 
Dim foundRNG As Range 
' 
' Macro1 
' 
' Input box to insert a date 

A = InputBox("Insert date of the last entry with format dd/mm/yyyy", "User date", Format(Now(), "dd/mm/yyyy")) 
If IsDate(A) Then 
    A = Format(CDate(A), "dd/mm/yyyy") 
Else 
    MsgBox "Date in the wrong format!" 
End If 

'Find the date above, in the variable A, in the Excel sheet 

Set foundRNG = Cells.Find(What:=A, After:=ActiveCell, LookIn:=xlFormulas, _ 
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _ 
MatchCase:=False, SearchFormat:=False) 

If foundRNG Is Nothing = False Then 
    foundRNG.Activate 
    Range(Selection, Selection.End(xlDown)).Select 
    Range(Selection, Selection.End(xlToRight)).Select 
    Selection.EntireRow.Delete 
Else 
    MsgBox "Entered date not found!" 
End If 

End Sub 
相关问题