none
How to use checkbox to show/hide bookmarked text? RRS feed

  • Question

  • I'm trying to create a document in Word 2016 that will allow a user to have the ability to check a checkbox or multiple checkboxes to make specific bookmarked text content appear within the document and to disappear when unchecked. 

    I have tried two different sets of VBA code while using an ActiveX Control type checkbox for the UI but nothing is working. To bookmark a set of text, I highlighted the text that I want and added a bookmark named "Bookmark1".  I am not a programmer by any means. What am I missing or what can i do to accomplish what I want? Thanks. 

    Set 1:

    Private Sub CheckBox1_Click()
    If Bookmarks("Bookmark1").Range.Font.Hidden = True Then
    Bookmarks("Bookmark1).Range.Font.Hidden = False
    Else
    Bookmarks("Bookmark1).Range.Font.Hidden = True
    End If
    End Sub

    Set 2:

    Private Sub CheckBox1_Click()
        Dim ShowText As Range
        Dim HideText As Range
        
        Set ShowText = ActiveDocument.Bookmarks("Bookmark1").Range
        Set HideText = ActiveDocument.Bookmarks("Bookmark1").Range
        
        If CheckBox1.Value = True Then
            ShowText.Font.Hidden = False
            HideText.Font.Hidden = True
        Else
            ShowText.Font.Hidden = True
            HideText.Font.Hidden = False
        End If

    End Sub

    Wednesday, November 29, 2017 8:30 PM

All replies

  • Without knowing the purpose of what you are attempting, who is going to use the document, or what the text is that you wish to optionally insert, it is difficult to determine which is the best method to approach this, but in any case I would avoid the use of hidden text.

    However if you must use active X check boxes the following will work, if the named bookmark exists. If it doesn't the macro does nothing.

    Option Explicit
    
    Private Sub CheckBox1_Click()
        If CheckBox1.Value = True Then
            FillBM "Bookmark1", "This is the text to go in the bookmark" & vbCr & _
                                "when the check box is checked."
        Else
            'clear the bookmark content'
            FillBM "Bookmark1", ""
        End If
    lbl_Exit:
        Exit Sub
    End Sub
    
    Private Sub FillBM(strbmName As String, strValue As String)
    'Graham Mayor - http://www.gmayor.com'
    Dim orng As Range
        With ActiveDocument
            On Error GoTo lbl_Exit
            Set orng = .Bookmarks(strbmName).Range
            orng.Text = strValue
            orng.Bookmarks.Add strbmName
        End With
    lbl_Exit:
        Set orng = Nothing
        Exit Sub
    End Sub
    


    Graham Mayor - Word MVP
    www.gmayor.com

    Thursday, November 30, 2017 5:42 AM