首页 > 解决方案 > 禁止特定表单控件按钮运行其分配的宏,即使它已被单击

问题描述

我希望能够阻止特定按钮(“按钮 4925”)运行其分配的宏,即使它被单击。基本上,当您单击它时,它要么什么都不做,要么显示一条消息,上面写着“这是一个无法删除的重要项目”换句话说,我希望只有在单击的按钮处于单元格 A12。否则,正常运行代码。考虑到我是 VBA 的初学者,我不知道该怎么做。一些信息: 该按钮是一个表单控制按钮。不是 Active X 的。它被工作表上的另一个宏复制和粘贴。分配的宏是在标准模块下编写的。分配的宏功能是删除相对范围的行。这是代码:

    Sub Delete_Button()

' Delete_Button Macro

' Step 1: Select the cell under the clicked button
Dim r As Range
Dim s As Object
Set r = ActiveSheet.Buttons(Application.Caller).TopLeftCell
r.Select

' Step 2: delete all buttons relative to the selected cell from step 1
StartCell = ActiveCell.Offset(-5, 0).Address
EndCell = ActiveCell.Offset(0, 0).Address

For Each s In ActiveSheet.DrawingObjects
If Not Intersect(Range(StartCell, EndCell), s.TopLeftCell) Is Nothing Then
        s.Delete
    End If
Next s

' Step 3: delete the rows relative to the selected cell from step 1
    ActiveCell.Offset(-7, 0).Rows("1:9").EntireRow.Select
    Selection.Delete Shift:=xlUp
    ActiveCell.Offset(-4, 0).Range("A1").Select

End Sub

标签: excelvbabutton

解决方案


让我们假设分配给按钮的宏的名称Button_4925_click然后在开头添加以下行,Exit Sub

Sub Button_4925_click ()
   Exit Sub
   ' remaining code will not be executed
End Sub

更新:根据添加的信息(评论和发布),您可以检查按钮的位置并退出子

Sub Button_4925_click ()
    Dim sh As Shape
    Set sh = ActiveSheet.Shapes("Button 4925")
    If sh.TopLeftCell.Address(False, False) = "A12" Then
       Exit Sub
    End If

    ' remaining code will only be be executed if         
    ' button is not located near cell A12

End Sub

推荐阅读