我有一个表单,用于设置包含内容的标签列表以及初始化时的附带复选框。
我想在点击按钮时检查复选框的值。
如何引用回复选项 - 我在创建它时将复选框称为数字(i的值)。
添加复选框的代码:
Sub addLabel()
Dim theCheck As Object
Dim theLabel As Object
Dim i As Long
Dim LastRow As Integer
LastRow = Worksheets("Assumptions").Cells(Rows.Count, "B").End(xlUp).Row
For i = 1 To LastRow
Set theLabel = UserForm1.Controls.Add("Forms.Label.1", "Assumption" & i, True)
With theLabel
.Name = "Assumption" & i
.Caption = Worksheets("Assumptions").Range("B" & i).Value ' & labelCounter
.Left = 156
.Width = 500
.Top = 138 + i * 20
End With
Set theCheck = UserForm1.Controls.Add("Forms.CheckBox.1", i, True)
With theCheck
.Name = i
.Left = 140
.Width = 10
.Top = 138 + i * 20
End With
Next
End Sub
我的最终目标是检查哪个复选框为“True”,然后如果为true,请将随附的标签内容输入工作表。
我目前的主要斗争是如何按名称引用复选框(例如,例如,将它们称为1-10的所有地方循环遍历它们。
由于
答案 0 :(得分:1)
要在表单中引用对象,可以使用以下语法
<Name of your form>.<Name of your control>
我可以相信像UserForm1.1
但之类的东西,这不是一个好主意,只能用一个数字来调用你的复选框,给它一个正确的名字。
我强烈建议您更改
With theCheck
.Name = i 'This is not great
.Left = 140
.Width = 10
.Top = 138 + i * 20
End With
更明确的内容,如
With theCheck
.Name = "cb" & i 'Not great but better
.Left = 140
.Width = 10
.Top = 138 + i * 20
End With
要浏览每个复选框并检查是否已选中,您可以使用类似
的内容'Go through each control in your UserForm
For Each myControl In UserForm1.Controls
'If the current control is a Checkbox
If (TypeName(myControl) = "Checkbox") Then
'Check it's value
If (myControl.Value = True) Then
'Do whatever you want
'You can access your checkbox properties with myControl.YOUR_PROPERTY
End If
End If
Next myControl