我有一段代码可以将输入字段从禁用更改为启用,如果勾选了相应的复选框,则会将颜色从灰色更改为白色。
有没有办法循环播放或调用所有复选框&输入字段没有每对的单独代码?
我的代码是:
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
tb01.Enabled = True
tb01.BackColor = vbWhite
Else: tb01.Enabled = False
tb01.BackColor = vb3DLight
End If
End Sub
Private Sub CheckBox2_Click()
If CheckBox2.Value = True Then
tb02.Enabled = True
tb02.BackColor = vbWhite
Else: tb02.Enabled = False
tb02.BackColor = vb3DLight
End If
End Sub
编辑:此代码位于UserForm
中答案 0 :(得分:0)
复选框是Excel中的一个集合,您可以执行以下操作:
Sub SelectCheckboxes()
Dim CB As CheckBox
For Each CB In Sheet1
If CB.Name <> Sheet1.CheckBoxes("SkipThisCheckbox").Name Then
CB.Value = 2
End If
Next CB
End Sub
您可以将值更改为所有复选框,但“SkipThisCheckbox”复选框除外。
编辑:我的想法是复选框是一个集合,我已将您的问题翻译为“告诉我如何选中/选中复选框,而不是一个一个”。
在表格上应该是这样的:
Private Sub CommandButton1_Click()
Dim cCont As Control
For Each cCont In Me.Controls
If TypeName(cCont) = "Checkbox" Then
Debug.Print cCont
'True or False if checked
'Write your logic here.
End If
Next cCont
End Sub
答案 1 :(得分:0)
更通用的方法是模块类1
下面是一个可能的应用程序,假设您的UserForm中的TextBoxes和CheckBoxes在“Name”属性基础上配对,如“CheckBox1” - “TextBox1”,“CheckBox2” - “TextBox2”,... < / p>
放置以下代码
Option Explicit
'declare class properties of CheckBox and TextBox type to be "paired" in every instance of this class. the CheckBox one will be associated to events
Public WithEvents ChkBox As MSForms.CheckBox ' ChkBox is a property of the class of type CheckBox. it's associated to events
Public TxtBox As MSForms.TextBox ' TxtBox is a property of the class of type TextBox
' events associated to ChkBox class property
Sub ChkBox_Change()
Call SetTexBox 'call the "method" (i.e. a Sub attached to the class) associated to ChkBox property state change
End Sub
Sub SetTexBox()
'sub that sets the state of the associated TextBox accordingly to the state of the associated CheckBox
With Me.ChkBox
If .value Then
TxtBox.Enabled = True
TxtBox.BackColor = vbWhite
Else
TxtBox.Enabled = False
TxtBox.BackColor = vb3DLight
End If
End With
End Sub
在项目中添加“课程模块”
点击插入 - &gt; VBA IDE主功能区菜单中的类模块
或右键单击VBA IDE项目窗口中的任意位置,然后选择插入 - &gt;后续子菜单中的类模块
展开项目窗口中的“类模块”节点
如果您没有看到项目窗口,可以通过单击View-&gt;打开它。主功能区菜单中的项目窗口,或按“Ctrl + R”
选择您添加的新类(应该是某些“Class1”或类似名称),并在属性窗口“名称”文本框中将其名称更改为“ChkBox_TxtBox_Class”
如果您没有看到属性窗口,可以通过单击View-&gt;打开它。主功能区菜单中的属性窗口或按“F4”
放置以下内容
(?:[0][0-9]|[1][012])(?::[0-5][0-9])?(?:[AP]M|[ap]m)|(?:[0-1][0-9]|2[0-3]):(?:[0-5][0-9])
运行你的日常工作