vba 根据单元格值向用户窗体添加复选框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15530443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:12:35  来源:igfitidea点击:

Add checkboxes to UserForm based on cell value

excelexcel-vbacheckboxvba

提问by hcsnemrebured

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.

我对 VBA 很陌生,只有 3 天……但我发现它非常有用且易于使用,但现在我遇到了问题。我需要使用不同的复选框制作用户窗体,但我需要根据工作表的一列中使用的信息自动添加它们。我相信我可以使用 For .. Each .. Next 但我真的不知道如何填写复选框。这是我现在唯一的解决方案,但我不能做不同的复选框,只有一个。

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!

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

回答by TheEngineer

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:

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

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.

您将需要修改代码以满足您的特定需求,但这会让您开始。

回答by Skip Intro

Have a look at this previous answer for a start as it explains the principals you need, I think.

我想,先看看这个以前的答案,因为它解释了你需要的原则。

Add Controls To A Frame

向框架添加控件

回答by Daniel Penny

UserForm1.Controls("Checkbox" & i).Value