Excel用户名表单呼叫checkbox的名称

我有一个表单,它在初始化时设置了一个包含内容和附带checkbox的标签列表。

我想检查单击button时的checkbox的值。

我如何参考checkbox – 我已经创build了一个数字(我的值)的checkbox。

添加checkbox的代码:

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 

我的最终目标是检查哪个checkbox是“True”,然后IF true是否将随附的标签内容input到工作表中。

我目前的主要努力是如何通过名称引用checkbox(例如循环遍历所有他们被称为1-10例如。

谢谢

要引用表单中的对象,可以使用以下语法

 <Name of your form>.<Name of your control> 

在你我可以相信像UserForm1.1这样的东西,但这不是一个好主意,只用一个数字来调用你的checkbox,给它一个正确的名字

我强烈build议你改变

 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 

循环显示表单中的每个checkbox

要通过每个checkbox,并检查是否选中,你可以使用这样的东西

 '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