答案 0 :(得分:4)
以下解决方案将“删除行”自定义菜单项添加到“行”上下文菜单。右键单击行选择器时,它看起来像这样。它提示用户在实际删除行之前确认行删除。
在项目级别的模块中,添加以下子例程...
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
答案 1 :(得分:1)
作为替代方案,您可以以几乎相同的方法重用现有的Delete选项。
在工作表模块中:
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