我想要一个宏,在单击文本值为“DELETE”的单元格时运行,并从单元格下方的一个单元格和“单元格”下面的19个单元格中删除整个行范围。
例如,如果单元格X7的值为“DELETE”,则单击它时将删除行6:26。
我到目前为止的代码是:
Private Sub Delete_Type(ByVal Target As Excel.Range)
If Target.Address = "$X$7" Then
Rows("(Row(), Column(),1, 4):((Row(), Column(), 4)+19)").Select
Selection.delete Shift:=xlUp
End If
End Sub
答案 0 :(得分:0)
试试这个:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
Dim firstRow As Long, lastRow As Long
Application.EnableEvents = False
On Error GoTo ErrorHandler
If UCase(Target.Value) = "DELETE" Then
'if target cell is in first row of sheet, we can't get row above
firstRow = Application.Max(Target.Row - 1, 1)
'if target cell is in last 19 rows of sheet, we can't get 19 rows below
lastRow = Application.Min(Target.Row + 19, Rows.Count)
Range(firstRow & ":" & lastRow).Delete Shift:=xlUp
End If
ExitHere:
Cancel = True
Application.EnableEvents = True
Exit Sub
ErrorHandler:
Resume ExitHere
End Sub
正如事件Worksheet_BeforeDoubleClick
所暗示的那样,每次双击任何单元格之前都会触发。
将以上代码放在Sheet
模块中: