简体   繁体   English

如何在VBA中使用复选框创建简单的用户窗体

[英]How to Create a Simple Userform with Checkboxes in VBA

I am extremely new to VBA and am trying to create a spreadsheet that uses a checkbox userform to populate a table in a spreadsheet. 我对VBA极为陌生,正在尝试创建一个电子表格,该电子表格使用复选框用户窗体填充电子表格中的表格。 I have been able to get the table to populate, but if a box is accidentally checked and is unchecked, the table remains populated. 我已经能够填充该表,但是如果意外选中了一个框且未选中该框,则该表仍会填充。 How do I get the table to go back to being blank after a box is unchecked and what is an efficient way to code the 33 checkboxes to populate the 33 spaces in the spreadsheet. 取消选中复选框后,如何使表格恢复为空白,这是对33个复选框进行编码以填充电子表格中33个空格的有效方法。 Please see the images attached to aid in my description. 请参阅所附图片以帮助我进行描述。

Thanks, 谢谢,

Userform Image 用户表单图片
在此处输入图片说明

Spreadsheet Image 试算表图片
在此处输入图片说明

Setting the CheckBox ControlSource Property to a range address will link it to the range. 将CheckBox ControlSource属性设置为范围地址会将其链接到该范围。 If the range isn't qualified A1 the Checkbox will link to the Worksheet that is the ActiveSheet when the Userform Opens. 如果范围不符合A1 ,则当用户窗体打开时,复选框将链接到作为ActiveSheet的工作表。 To qualify the address add the Range's parent Worksheet's Name in single quotes followed by a exclamation mark and finally the ranges relative address 'Check List'!A1 . 要使地址合格,请在单引号中加上范围的父级工作表名称,后加上感叹号,最后是范围的相对地址'Check List'!A1

Initially, the Checkbox will be grayed out indicating that the linked cell is empty. 最初,复选框将显示为灰色,表明链接的单元为空。 When you check and uncheck it the linkedcell value will toggle between True and False. 当您选中和取消选中它时,链接的单元格值将在True和False之间切换。

控制源属性图像

演示用户表单Gif

Demo Userform Code 演示用户表单代码

Private Sub UserForm_Initialize()
    Dim Left As Single, Top As Single
    Dim cell As Range, row As Range, check As MSForms.CheckBox
    Top = 25
    Left = 25
    With Worksheets("Check List")
        For Each row In .Range("A2:K4").Rows
            For Each cell In row.Cells
                Set check = Me.Controls.Add("Forms.CheckBox.1")
                With check
                    .ControlSource = "'" & cell.Parent.Name & "'!" & cell.Address(RowAbsolute:=False, ColumnAbsolute:=False)
                    .Left = Left
                    .Top = Top
                    Left = Left + 12
                End With
            Next
            Left = 25
            Top = Top + check.Height + 2
        Next
    End With
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM