根据单元格值将复选框添加到用户窗体

问题描述:

我刚刚接触VBA,只有3天的时间...但是我发现它非常有用且易于使用,但是现在我遇到了问题.我需要使用不同的复选框制作一个用户窗体,但是我需要根据工作表的一列中使用的信息自动添加它们.我相信我可以使用For ..每个..接下来,但我真的不知道如何填写复选框.这是我目前拥有的唯一解决方案,但我无法与众不同Checkboxes,只有一个.

I'm very new to VBA, just 3 days... but i found it very useful and easy to use, but now i'm facing a problem. I need to make a UserForm with different Checkboxes, but i need them to be added automatically based on the information used in one of the columns of a Sheet. I believe i can use the For .. Each .. Next but i really don't know how to fill the Checkboxes. This is the only solution that i have right now, but i can't make differents Checkboxes, only one.

For Each rCell In Range("B1:B" & LastRow)
    If rCell.Value <> "" Then
        UserForm1.Controls.Add ("Forms.CheckBox.1")
    End If
Next

我需要做的另一件事是在添加复选框后填充复选框的属性,以便在此之后可以使用这些值.

One more thing that i need to do is fill the properties of the Checkbox once it is added, so i can work with the values after that.

任何帮助将不胜感激,谢谢!

Any help would be appreciated, Thanks!

我确定您之前已经获得了答案,但是由于这是我的Google搜索中出现的,所以我想我会发布另一个答案.将以下代码放在您的UserForm中:

I'm sure you've gotten your answer before now, but since this came up in a Google search of mine, I thought I'd post another answer. Place the following code in your UserForm:

Option Explicit

Private Sub UserForm_Initialize()

Dim curColumn   As Long
Dim LastRow     As Long
Dim i           As Long
Dim chkBox      As MSForms.CheckBox

curColumn = 1 'Set your column index here
LastRow = Worksheets("Sheet1").Cells(Rows.Count, curColumn).End(xlUp).Row

For i = 1 To LastRow
    Set chkBox = Me.Controls.Add("Forms.CheckBox.1", "CheckBox_" & i)
    chkBox.Caption = Worksheets("Sheet1").Cells(i, curColumn).Value
    chkBox.Left = 5
    chkBox.Top = 5 + ((i - 1) * 20)
Next i

End Sub

您将需要修改代码以适合您的特定需求,但这将使您入门.

You will need to modify the code to suit your specific needs, but that will get you started.