Search code examples
vbams-wordhide

How can I hide characters in Microsoft Word using VBA?


I would like to hide characters in Microsoft Word, more specifically hide the text between some characters.

For example, if I got this:

::00-58-96:: Hello there
::00-58-97:: This is a test
::00-58-98:: Nothing else
::00-58-99:: Good bye !

I would like to hide the text between the

::        ::

And the result would be

Hello there
This is a test
Nothing else
Good bye !

Another example would be

==this:example== Again this
==this:example== Is a
==this:example== Test

And the result would be

Again this
Is a
Test

I do not know if I exposed my problem well.

I've already tried to do this (some other people help me) but this replace the text, not hide it:

Sub l()
'
'
'
    ActiveDocument.Range.Select '

With Selection.Find
     .MatchWildcards = True
     .Text = "::*::"
     .Replacement.Text = ""
     .Execute Replace:=wdReplaceAll, Forward:=True, _
     Wrap:=wdFindContinue
End With


End Sub


UPDATE:

Word is still crashing/just hidden the first line of my document, I've modify just one line as follows :

Private Sub SelFind()


    Dim Rng As Range
    Dim Fnd As Boolean

G:
    Set Rng = ActiveDocument.Range


    With Rng.Find
        .ClearFormatting
        .MatchWildcards = True
        .Execute FindText:=";;*;;*;;", Forward:=True, _
                 Format:=False, Wrap:=wdFindStop
        Fnd = .Found
    End With

    If Fnd = True Then
        With Rng
            .MoveStart wdWord, 0
            .Select
            With .Font
                .Hidden = True
            End With
        End With
        GoTo G

    Else:

    MsgBox "All done"

    End If
End Sub


Solution

  • Try this:

    Private Sub SelFind()
    
    
        Dim Rng As Range
        Dim Fnd As Boolean
    
    G:
        Set Rng = ActiveDocument.Range
    
    
        With Rng.Find
            .ClearFormatting
            .MatchWildcards = True
            .Execute FindText:="::*::", Forward:=True, _
                     Format:=False, Wrap:=wdFindStop
            Fnd = .Found
        End With
    
        If Fnd = True Then
            With Rng
                .MoveStart wdWord, 0
                .Select
                With .Font
                    .Hidden = True
                End With
            End With
            GoTo G
    
        Else:
    
        MsgBox "All done"
    
        End If
    End Sub
    

    Took help from this Answer