我有一个vba userForm,上面有36个按钮。当我的某个传感器上的值达到一定数量时,我想禁用所有按钮。现在,每按一次按钮,我正在引用的电子表格上的数字就会增加一个。当数字达到3时,我想禁用所有按钮。
答案 0 :(得分:5)
将所有按钮放在Frame对象中,然后只禁用整个框架。这也会禁用框架内的所有内容。
或者,根据您的上一个问题,您可以使用以下代码:
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
理想情况下,您可能希望将Control对象转换为像Thomas建议的按钮。
答案 1 :(得分:5)
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
如果您有其他不想禁用的按钮,解决方法是使用Tag属性。在要启用或禁用相同值的所有按钮上设置Tag属性。然后,您可以查看该值并启用/禁用它们。另一种方法是将它们命名为相同的前缀或后缀,并在代码中检查它。
<强>加成强>
顺便说一下,Control对象没有Enabled属性。因此,您必须将其“转换”为CommandButton才能将其禁用。显然,Control对象确实具有Enabled属性,但它不会在intellisense中显示。但是,您仍应尝试将Control转换为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
答案 2 :(得分:0)
@Mike:试试 -
If Sheets("Sheet1").Range("A1").Value = 3 Then
UserForm1.CommandButton1.Enabled = True
Else
UserForm1.CommandButton1.Enabled = False
End If
(将Sheet1
,A1
,UserForm1
和CommandButton1
替换为您工作簿的正确