禁止特定窗体控件按钮运行其分配的宏,即使单击了该按钮也是如此



我希望能够阻止特定按钮("按钮 4925"(运行其分配的宏,即使单击它也是如此。基本上,当您单击它时,它要么不执行任何操作,要么显示一条消息,指出" 这是无法删除的基本项目" 换句话说,我希望只有在单击的按钮位于单元格 A12 中时才能退出潜艇。否则,请正常运行代码。考虑到我是VBA的初学者,我不知道该怎么做。 一些信息: 该按钮是窗体控件按钮。不是活动 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

您必须以某种方式"告诉"代码,它不得删除范围。

因此,我建议您在保留按钮代码的模块(在声明区域中(之上创建一个Private变量:

Private stopButCode As Boolean

比,您必须使此变量True。使用复选框或其他控件中的一段代码使其True

必须按如下方式调整按钮代码:

If Not stopButCode Then
'delete whatever is to be deleted
Else
MsgBox "Deletion not allowed..."
Exit Sub
End If

编辑: 如果您希望代码仅在按钮位于单元格"A12"上时才起作用,则可以按如下方式使用"调整代码":

Dim r As Range
Dim s As Object
Set r = ActiveSheet.Buttons(Application.Caller).TopLeftCell
If r.Address = "$A$12" then Exit Sub
'here follows your existing code...

最新更新