userform.label上的VBA Excel循环

Iam通过代码创build我的标签和checkbox:

i = 1 While Not Sheets("I_M_1_1PW").Cells(9 + i, 43) = "koniec" Set theLabel = UserForm1.Controls.Add("Forms.Label.1", labelCounter, True) With theLabel .Caption = Sheets("I_M_1_1PW").Cells(9 + i, 43) .Left = 10 .Width = 100 .Top = 13 * labelCounter Debug.Print labelCounter & " " & theLabel.Caption End With Set chkbox = UserForm1.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i) chkbox.Caption = Sheets("I_M_1_1PW").Cells(9 + i, 44) chkbox.Left = 100 chkbox.Width = 75 chkbox.Top = 13 * labelCounter i = i + 1 labelCounter = labelCounter + 1 

我可以通过代码search活动checkbox:

 For j = 1 To Granica - 1 If UserForm1.Controls("CheckBox_" & j).Value = True Then Wynik1 = UserForm1.Controls("CheckBox_" & j).Caption + Wynik1 '* Wzorce = Wzorce + UserForm1.label(j).Caption End If Next 

但在'*的地方我有问题,不能采取label.caption当我使用UserForm1.Controls(j).Caption它遍历所有部分user.form不仅标签。

你必须使用

 Wzorce = Wzorce + UserForm1.Controls(CStr(j)).Caption 

这里跟着你的代码的一些其他可能的增强

 Dim theLabel As MSForms.Label, chkbox As MSForms.CheckBox Dim Wynik1 As Variant, Wzorce As Variant i = 1 While Not Sheets("I_M_1_1PW").Cells(9 + i, 43) = "koniec" Set theLabel = UserForm1.Controls.Add("Forms.Label.1", i, True) With theLabel .Caption = Sheets("I_M_1_1PW").Cells(9 + i, 43) .Left = 10 .Width = 100 .Top = 13 * i Debug.Print i & " " & theLabel.Caption End With Set chkbox = UserForm1.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i) With chkbox .Caption = Sheets("I_M_1_1PW").Cells(9 + i, 44) .Left = 100 .Width = 75 .Top = 13 * i End With i = i + 1 Wend ... For j = 1 To Granica - 1 If UserForm1.Controls("CheckBox_" & j).Value = True Then Wynik1 = chkboxes(j).Caption + Wynik1 Wzorce = Wzorce + UserForm1.Controls(j).Caption End If Next 

最后,在这里遵循上面相同的代码,但使用控制数组,可能会使您的代码更具可读性和可维护性:

 Dim theLabel As MSForms.Label, chkbox As MSForms.CheckBox Dim labels() As MSForms.Label, chkboxes() As MSForms.CheckBox i = 1 While Not Sheets("I_M_1_1PW").Cells(9 + i, 43) = "koniec" Set theLabel = UserForm1.Controls.Add("Forms.Label.1", i, True) With theLabel .Caption = Sheets("I_M_1_1PW").Cells(9 + i, 43) .Left = 10 .Width = 100 .Top = 13 * i Debug.Print i & " " & theLabel.Caption End With ReDim Preserve labels(1 To i) Set labels(i) = theLabel Set chkbox = UserForm1.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i) With chkbox .Caption = Sheets("I_M_1_1PW").Cells(9 + i, 44) .Left = 100 .Width = 75 .Top = 13 * i End With ReDim Preserve chkboxes(1 To i) Set chkboxes(i) = chkbox i = i + 1 Wend ... For j = 1 To Granica - 1 If chkboxes(j).Value = True Then Wynik1 = chkboxes(j).Caption + Wynik1 Wzorce = Wzorce + labels(j).Caption End If Next End Sub 

假设你的控件是成对的,那应该是:

 Wzorce = Wzorce + UserForm1.Controls("" & j).Caption 

不过我认为你应该像checkbox一样命名标签。

太棒了。

 Wzorce = Wzorce + UserForm1.Controls("label_" & j).Caption 

Ty user3598756。