问题
Okay so here is the problem: In my user form, I have 2 checkboxes. I want to be able to use the value of the checkbox to perform a certain job.
Example:
Sub main()
UserForm1.Show
If UserForm1.CheckBox1.Value=True Then
MsgBox("Awesome")
End If
End Sub
Now my problem with this is that it keeps giving me run time error 424. Can anyone help me with this? Your help is greatly appreciated. Thank you.
Update:
Sub main()
UserForm1.Show
If UserForm1.CheckBox1.Value=True Then
Worksheets(1).Activate
If UserForm1.CheckBox1.Value=True Then
MsgBox("Awesome")
End If
End If
End Sub
Okay now it stops after worksheets(1).Activate
.
Your help is greatly appreciated.
Thank you.
回答1:
Solution: This code works for me:
Sub main()
If UserForm1.CheckBox1.Value = True Then
MsgBox "Checkbox is checked"
End If
End Sub
Explanation: The error appears because you did not specify which object (in this case: which form) CheckBox1
belongs to. Hence I added the UserForm1.
in the If
statement. Secondly, CheckBox1.Value
is a boolean property, i.e. the value will be True
when checked, not 1
.
Additional information: Please note that running the If
clause just after UserForm1.Show
(like you did in your example) will never work in case you intend to select the checkboxes after the .Show
command. The form will be shown and the If
clause be run before you even had the time to select the checkbox. So the code in my answer should go to another Sub, e.g. the one run when you click a button in your form (do you have some sort of "OK" or "Close" button on it? If yes, double click the button in the macro editor and add the code there). Let me know if you need more context.
Update (as requested in the comments): Here's what I have:
Sub a()
' This launches the form
' I added this to a normal Module in the
' VBA editor
UserForm1.Show
End Sub
Private Sub CommandButton1_Click()
' This is what is executed when clicking
' the "OK" button
' To add this code, add a button to your
' form, double click it and paste this code
If UserForm1.CheckBox1.Value = True Then
Worksheets(1).Activate
MsgBox "Awesome"
End If
' Update 2: Close form but keep
' Checkbox1.Value available
Userform1.Hide
End Sub
Running a
(from the "Macros" dialogue on the "Developer" tab) gives me:
Selecting the checkbox and clicking OK returns this:
来源:https://stackoverflow.com/questions/30557232/how-to-fix-run-time-error-424-when-accessing-the-value-of-a-checkbox-in-excel-vb