提示用户确认删除行

问题描述 投票:-1回答:2

我的用户需要能够删除行。他们很舒服右键单击行选择器并选择“删除”。如何添加用户确认他们要删除行的提示?

enter image description here

请注意,Worksheet_BeforeDelete()不会捕获行删除。

excel vba excel-vba
2个回答
4
投票

以下解决方案将“删除行”自定义菜单项添加到行上下文菜单。右键单击行选择器时看起来像这样。在实际删除行之前,它会提示用户确认删除行...

Confirmation message

在项目级模块中,添加以下子例程......

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
投票

作为替代方法,您可以使用几乎相同的方法重用现有的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
© www.soinside.com 2019 - 2024. All rights reserved.