我在Excel VBA中使用以下代码(使用Excel 2010),以欧洲格式(dd / mm / yyyy)查找特定日期,然后取消单元格下方的行(其中包含该日期) :
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
未设置对象变量。
非常感谢你的帮助。
答案 0 :(得分: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