如何使用 VBA 从 Excel 用户表单中读取复选框的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12379613/
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
How to use VBA to read the values of a checkbox from an Excel userform
提问by user1664313
I have created a userform that contains two checkboxes. I would like to be able to do different things depending on whether each box is checked or unchecked. However, it seems like no matter what I do, it will always tell me the original value of the checkboxes (false and false). Here is the code attached to clicking CommandButton1:
我创建了一个包含两个复选框的用户表单。我希望能够根据每个框是选中还是未选中来做不同的事情。但是,似乎无论我做什么,它都会告诉我复选框的原始值(false 和 false)。这是附加到单击 CommandButton1 的代码:
Private Sub CommandButton1_Click()
ReadData
End Sub
And here ReadData:
在这里读取数据:
Sub ReadData()
Dim myForm As UserForm
Set myForm = UserForms.Add("ComplaintEntryForm")
Debug.Print (myForm!CheckBox1.Name)
Debug.Print (myForm!CheckBox1.Value)
Debug.Print (myForm!CheckBox2.Name)
Debug.Print (myForm!CheckBox2.Value)
End Sub
No matter how the boxes are checked, the immediate window always shows this:
无论如何选中这些框,即时窗口始终显示以下内容:
VBA.UserForms.Add("ComplaintEntryForm").Show
CheckBox1
False
CheckBox2
False
I have a screenshot of the whole operation but it won't let me upload it because I'm a new user.
我有整个操作的屏幕截图,但它不会让我上传它,因为我是新用户。
采纳答案by barrowc
Try this method to load and show the form (this goes in a normal module):
试试这个方法来加载和显示表单(这在一个普通模块中):
Sub main()
Dim myForm As ComplaintEntryForm
Set myForm = New ComplaintEntryForm
myForm.Show
Set myForm = Nothing
End Sub
In the UserForm's own module, add the following:
在 UserForm 自己的模块中,添加以下内容:
Private Sub CheckBox1_Change()
readData
End Sub
Private Sub CheckBox2_Change()
readData
End Sub
Private Sub UserForm_Initialize()
Me.CheckBox1.Value = True
Me.CheckBox2.Value = False
End Sub
Private Sub readData()
Debug.Print Me.CheckBox1.Name
Debug.Print Me.CheckBox1.Value
Debug.Print Me.CheckBox2.Name
Debug.Print Me.CheckBox2.Value
End Sub
I've initialized the two checkboxes to specific values in the Initialize
event. This means we are certain about the state the form will start in
我已将两个复选框初始化为Initialize
事件中的特定值。这意味着我们可以确定表单将在哪个状态开始