Thursday, September 8, 2011

Format part of a found text string



Word's replace function is capable of applying formatting to found strings, but only the whole of a found string. Sometimes it is desirable to format only part of the string e.g. you may search for the chemical symbol for water H2O in order to format the 2 as subscript. The replace function cannot do that. With this example the simplest solution is to copy the correctly formatted version to the clipboard and replace the find string H2O with the clipboard contents H2O i.e. put ^c  in the replace with box.
OR
You could create a macro to do so. The following shows two techniques for selecting a digit from a found item.
Sub Subscript2_in_H2O()

Dim rText As Range

With Selection

    .HomeKey wdStory

    With .Find

        .ClearFormatting

        .Replacement.ClearFormatting

        Do While .Execute(findText:="H2O", _

            MatchWildcards:=False, _

            Wrap:=wdFindStop, _

            Forward:=True) = True

            Set rText = Selection.Range 'The found text

            With rText 'Do what you want with the found text

                'move the start position of the found text one character right

                .MoveStart Unit:=wdCharacter, Count:=1

                'move the end position of the found text one character to the left

                .MoveEnd Unit:=wdCharacter, Count:=-1

                'the text string is now one character long i.e. the "2"

                .Font.Subscript = True 'apply subscript to the remaining text string

            End With

        Loop 'and look for the next match

    End With

End With

End Sub
or even simpler
Sub Subscript2_in_H2ORev1()
With Selection
    .HomeKey wdStory
       
With .Find
            .ClearFormatting
            .Replacement.ClearFormatting
           
Do While .Execute(findText:="H2O", _

                     MatchWildcards:=False, _

                     Wrap:=wdFindStop, _

                     Forward:=True) = True
              
'Do what you want with the found text (Selection.Range)

               'In this case format the second character as subscripted
                Selection.Range.Characters(2).Font.Subscript =
True
           
Loop 'and look for the next match
       
End With
End With
End Sub

No comments:

Post a Comment