PDA

View Full Version : Word - show/hide bookmark text based on checkbox



adhoc
04-18-2024, 12:43 AM
Hi - apologies if I'm misunderstanding as I'm new to this but I am just wanting to show or hide bookmark text in a Word document based on a checkbox being ticked on or off.

I have tried:

Private Sub Document_Open() ' This subroutine runs when the Word document is opened
' It ensures that the text linked to checkboxes is hidden by default
HideTextBasedOnCheckbox
End Sub


Private Sub CheckBox1_Click()
' This subroutine is linked to the checkbox's click event
HideTextBasedOnCheckbox
End Sub


Private Sub HideTextBasedOnCheckbox()
' This subroutine checks the state of the checkbox and shows/hides text accordingly
Dim cb As CheckBox
Set cb = ActiveDocument.FormFields("CheckBox1").CheckBox

If cb.Value = True Then
' If the checkbox is ticked, show the text
ActiveDocument.Bookmarks("TextToDisplay").Range.Font.Hidden = False
MsgBox "The checkbox is ticked!", vbInformation
Else
' If the checkbox is not ticked, hide the text
ActiveDocument.Bookmarks("TextToDisplay").Range.Font.Hidden = True
End If
End Sub




Is there something wrong with the above code?

Thanks
T

georgiboy
04-18-2024, 01:32 AM
It looks to me like you are mixing the use of Content Controls and ActiveX objects. The sub 'CheckBox1_Click' refers to an ActiveX object, however, 'ActiveDocument.FormFields("CheckBox1").CheckBox' does not refer to an ActiveX control.

I have updated the code below and added an ActiveX checkox on the attached file.


Private Sub Document_Open() ' This subroutine runs when the Word document is opened
' It ensures that the text linked to checkboxes is hidden by default
HideTextBasedOnCheckbox
End Sub


Private Sub CheckBox1_Click()
' This subroutine is linked to the checkbox's click event
HideTextBasedOnCheckbox
End Sub


Private Sub HideTextBasedOnCheckbox()
' This subroutine checks the state of the checkbox and shows/hides text accordingly
Dim cb As Object
Set cb = CheckBox1

If cb = True Then
' If the checkbox is ticked, show the text
ActiveDocument.Bookmarks("TextToDisplay").Range.Font.Hidden = False
Else
' If the checkbox is not ticked, hide the text
ActiveDocument.Bookmarks("TextToDisplay").Range.Font.Hidden = True
End If
End Sub

adhoc
04-18-2024, 06:08 PM
Thank you!!

georgiboy
04-18-2024, 10:24 PM
You are welcome and also, welcome to the forum.