有没有办法一次禁用多个button?

我有一个vba userForm有36个button。 我想在我的一个展位上的某个值达到某个数时禁用所有的button。 现在,每点击一个button,电子表格上的数字就会上升一个。 当数字达到三时,我想禁用所有的button。

Dim oCtrl As Control Dim oButton As CommandButton For Each oCtrl In MyForm.Controls If oCtrl.Tag = "SomeValue" Then Set oButton = oCtrl oButton.Enabled = False End If Next Set oCtrl = Nothing Set oButton = Nothing 

如果您有其他不想禁用的button,则解决scheme是使用Tag属性。 将所有要启用或禁用的button上的Tag属性设置为相同的值。 然后你可以看看这个值,并启用/禁用它们。 另一种方法是给它们命名相同的前缀或后缀,并检查代码中的内容。

加成

顺便说一句,控制对象没有启用属性。 所以你必须把它“投”到CommandButton来禁用它 。 显然,Control对象具有Enabled属性,但不显示为intellisense。 但是,您仍然应该尝试将控件转换为CommandButton,以确保您拥有这些控件。 这是一个扩展版本:

 Dim oCtrl As Control Dim oButton As CommandButton For Each oCtrl In MyForm.Controls If oCtrl.Tag = "SomeValue" Then On Error Resume Next Set oButton = oCtrl On Error GoTo 0 If Not oButton Is Nothing Then oButton.Enabled = False End If End If Next Set oCtrl = Nothing Set oButton = Nothing 

将所有button放在一个Frame对象中,然后closures整个框架。 这也将禁用框架内的一切。

另外,根据你最后一个问题,你可以使用这个代码:

 Dim counter As Integer Private Sub btn1_Click() CaptureImage (btn1.Name) End Sub Private Sub btn2_Click() CaptureImage (btn2.Name) End Sub Private Sub btn3_Click() CaptureImage (btn3.Name) End Sub Private Sub UserForm_Activate() counter = 1 End Sub Private Sub CaptureImage(ByVal btnName As String) Controls("capture" & counter).Picture = Controls(btnName).Picture counter = counter + 1 If counter > 3 Then DisableButtons End If End Sub Private Sub DisableButtons() Dim ctl As Control For Each ctl In UserForm1.Controls If Left(ctl.Name, 3) = "btn" Then ctl.Enabled = False End If Next End Sub 

理想情况下,你会想像托马斯build议的那样将控件对象转换为button。

@Mike:试试 –

 If Sheets("Sheet1").Range("A1").Value = 3 Then UserForm1.CommandButton1.Enabled = True Else UserForm1.CommandButton1.Enabled = False End If 

(replaceSheet1A1UserForm1CommandButton1与您的工作簿正确的)