PDA

View Full Version : how to change a forms checkbox if another is selected?



perry_swain
07-18-2012, 07:21 PM
hi there, i have a macro for word 2010 that changes the value of other checkboxes when one is selected, i.e there is 5 checkboxes for one question, heres the code that i made to successfully do this:

Private Sub CheckBox1_Click()
If Me.CheckBox1.Value Then
Me.CheckBox2.Value = False
Me.CheckBox3.Value = False
Me.CheckBox4.Value = False
Me.CheckBox5.Value = False
End If
End Sub

then i repeat that for the next check box i.e:

Private Sub CheckBox2_Click()
If Me.CheckBox2.Value Then
Me.CheckBox1.Value = False
Me.CheckBox3.Value = False
Me.CheckBox4.Value = False
Me.CheckBox5.Value = False
End If
End Sub

what i want to do is simplify this code, i tryed to do something like this that i found in a topic:

Private Sub CheckBox1_Change()
SetCheckBoxes 1
End Sub

Private Sub CheckBox2_Change()
SetCheckBoxes 2
End Sub

Private Sub CheckBox3_Change()
SetCheckBoxes 3
End Sub

Private Sub CheckBox4_Change()
SetCheckBoxes 4
End Sub

Private Sub CheckBox5_Change()
SetCheckBoxes 5
End Sub


Private Function SetCheckBoxes(CBIndex As Long)
Dim x As Long

If Me.OLEObjects("CheckBox" & CBIndex).Object.Value Then
For x = 1 To 5
If x <> CBIndex Then
Me.OLEObjects("CheckBox" & x).Object.Value = False
End If
Next x
End If
End Function

the problem with that is that i get an error saying it cannot find the object :/ if anyone could help me with this that would be great :D

fumei
07-18-2012, 10:56 PM
Change OLEObjects to Controls.
Private Sub SetCheckBoxes(CBIndex As Long)
Dim x As Long

If Me.Controls("CheckBox" & CBIndex).Object.Value Then
For x = 1 To 5
If x <> CBIndex Then
Me.Controls("CheckBox" & x).Object.Value = False
End If
Next x
End If
End Sub

BTW: I changed your Function to Sub, as it really is a Sub rather than a Function.

perry_swain
07-19-2012, 02:47 PM
thanks for the reply, but that doesnt solve the problem, i still get the error method or data member not found, heres what i changed the code to:


Private Sub CheckBox1_Change()
SetCheckBoxes 1
End Sub

Private Sub CheckBox2_Change()
SetCheckBoxes 2
End Sub

Private Sub CheckBox3_Change()
SetCheckBoxes 3
End Sub

Private Sub CheckBox4_Change()
SetCheckBoxes 4
End Sub

Private Sub CheckBox5_Change()
SetCheckBoxes 5
End Sub

Private Sub SetCheckBoxes(CBIndex As Long)
Dim x As Long

If Me.Controls("CheckBox" & CBIndex).Object.Value Then
For x = 1 To 5
If x <> CBIndex Then
Me.Controls("CheckBox" & x).Object.Value = False
End If
Next x
End If
End Sub

fumei
07-20-2012, 12:09 PM
If I make a userform with five checkboxes, and copy that code it works perfectly. Not sure what you "changed". But I used your code, and it works perfectly.

Could you have changed a name of a checkbox?

I get no errors whatsoever.