以下解决方案将“删除行”自定义菜单项添加到行上下文菜单。右键单击行选择器时看起来像这样。在实际删除行之前,它会提示用户确认删除行...
在项目级模块中,添加以下子例程......
Public Sub DeleteRow()
If MsgBox("Are you sure?", vbOkCancel, "Confirm Delete") = vbOk Then
Selection.EntireRow.Delete
End If
End Sub
在工作表代码模块中,添加以下子例程......
Private Sub Worksheet_Activate()
'reset to standard context menu before adding new option
Application.CommandBars("Row").Reset
'add custom row deletion call
With Application.CommandBars("Row").Controls.Add
.Caption = "Delete Row"
.Style = msoButtonCaption
.OnAction = "DeleteRow"
End With
End Sub
Private Sub Worksheet_Deactivate()
'get rid of the customization when you're done with this sheet
Application.CommandBars("Row").Reset
End Sub
作为替代方法,您可以使用几乎相同的方法重用现有的Delete选项。
在Sheet模块中:
Option Explicit
Private Sub Worksheet_Activate()
Dim c As CommandBarButton
For Each c In Application.CommandBars("row").Controls
If c.Caption = "&Delete" Then
c.OnAction = "delete_row"
Exit For
End If
Next
End Sub
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
Set right_click_target = Target
End Sub
Private Sub Worksheet_Deactivate()
Dim c As CommandBarButton
For Each c In Application.CommandBars("row").Controls
If c.Caption = "&Delete" Then
c.OnAction = ""
Exit For
End If
Next
End Sub
在您的独立模块中:
Option Explicit
Public right_click_target As Range
Public Sub delete_row()
If MsgBox("Are you sure you want to delete this row?", vbYesNo, "Deletion") = vbYes Then
right_click_target.Delete
End If
End Sub