Francis Luong

View Original

Word Macro - Find lines with "fluong" and underline to end-of-line

I wrote a Word VBA macro to do some stuff I was too lazy to do by hand. I wanted to underline lines which start with my username. Now finding and underlining text is not a big deal, but extending the selection after finding it complicates matters.

This is probably not the best way to do things but it’s a good start for me. If it helps you, send me a tweet and let me know @francisluong.

http://codetidy.com/paste/embed/5853

Sub underline_fluong()
'
' underline_fluong Macro
' Find instances of "fluong" which are not underlined and:
'  - extend selection to end of line`
'  - underline it
'

Dim iCount As Integer
Dim searchText As String
searchText = "fluong"

Selection.HomeKey Unit:=wdStory

With Selection.Find
    .ClearFormatting
    .Forward = True
    .Wrap = wdFindContinue
    .Text = searchText
    .Font.Underline = wdUnderlineNone
    .Execute
End With

Do While Selection.Find.Found = True And iCount < 1000

    iCount = iCount + 1

    Selection.HomeKey Unit:=wdStory
    Selection.Find.Execute

    If Selection.Find.Found Then
        Selection.EndOf Unit:=wdLine, Extend:=wdExtend
        Selection.Font.Underline = wdUnderlineSingle

        With Selection.Find
            .ClearFormatting
            .Forward = True
            .Wrap = wdFindContinue
            .Text = searchText
            .Font.Underline = wdUnderlineNone
        End With
    End If
Loop

End Sub