On a form, I have 20 checkboxes for user to select from. I need a command button that will allow the user to click on this button, and all the checkboxes are selected. I've read where I can use collection controls, but I can't figure out the code.
Option Compare Database
Option Explicit
Dim collCheckBox As Collection
Private Sub Form_Load()
Dim ctrl As Control
Set collCheckBox = New Collection
For Each ctrl In Me
If ctrl.Tag = "1" Then
collCheckBox.Add ctrl
End If
Next
End Sub
Private Sub MyButton_Click()
Dim m As Integer
Dim n As Integer
m = collCheckBox.Count
For n = 1 To m
collCheckBox.Item(n) = True
Next
End Sub
Dim ctrl As Control
For Each ctrl In Me.Controls
If ctrl.ControlType = acCheckBox Then
ctrl.Value = True
End If
Next
[code]
You could give users another button to "De-select" all checkboxes by using the following code.
[code]
Dim ctrl As Control
For Each ctrl In Me.Controls
If ctrl.ControlType = acCheckBox Then
ctrl.Value = False
End If
Next
[code]
Private Sub btnCheckTrue_Click
CheckBoxesSet(True)
End Sub
Private Sub btnCheckFalse_Click
CheckBoxesSet(False)
End Sub
Private Sub CheckboxesSet(Checked as Boolean)
Dim m As Integer
Dim n As Integer
m = collCheckBox.Count
For n = 1 To m
collCheckBox.Item(n) = Checked
Next
End Sub
Code:Private Sub CheckboxesSet(Checked as Boolean) Dim m As Integer Dim n As Integer m = collCheckBox.Count For n = 1 To m collCheckBox.Item(n) = Checked Next End Sub
Dim chkBox As CheckBox
For Each chkBox In collCheckBox
chkBox = Checked
Next
Private Sub CheckboxesSet(Checked As Boolean)
Dim ctrl As Control
For Each ctrl In Me.mySubForm.Form
ctrl = Checked
Next
End Sub
I only posted the collection solution because that is what the OP asked about.Galaxiom, I like your idea of using a collection.
Er maybe this isn't so good. It two forms trying to edit the same record at the same timeInterestingly, we could put all our check boxes in a sub form and then just iterate the entire collection. This negates the need for any On Load code. So the code would be:
Code:Private Sub CheckboxesSet(Checked As Boolean) Dim ctrl As Control For Each ctrl In Me.mySubForm.Form ctrl = Checked Next End Sub
Chris
I think I've found a solution...Er maybe this isn't so good. It two forms trying to edit the same record at the same time. Is there a way round this?
Public Function fnOneOrMoreChecked() As Boolean
On Error GoTo Err_fnOneOrMoreChecked_Error
Dim ctrl As Control
For Each ctrl In Me.Controls
If ctrl.ControlType = acCheckBox Then
If ctrl.Value = True Then
fnOneOrMoreChecked = True
GoTo Exit_ErrorHandler
End If
End If
Next
Exit_ErrorHandler:
Exit Function
Err_fnOneOrMoreChecked_Error:
MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure fnOneOrMoreChecked "
Resume Exit_ErrorHandler
End Function
[code]
I think I've found a solution...
The tab control can be used as a container. Setting the Style of the tab control to None removes the tabs. And then setting the back style to transparent makes the control invisible.