Search code examples
vbams-wordfind-replacemsstyles

Microsoft Word VBA Macro - One Paragraph Find-Replace Styles


I am executing a style search in Microsoft Word using a VBA Macro. My goal is to perform certain actions once for every style found in the document.

The macro works correctly on documents that have at least two paragraphs, but the macro does not alert the style correctly in a document that has exactly one paragraph in it. It seems strange that when I enter a new paragraph mark, the styles are found, even though I did not add any new text or styles to the document, just an extra blank paragraph mark. Does anyone know what is wrong with my macro and how I can fix this? Thanks for taking a look.

Sub AlertAllStylesInDoc()
    Dim Ind As Integer
    Dim numberOfDocumentStyles As Integer
    Dim styl As String
    Dim StyleFound As Boolean

    numberOfDocumentStyles = ActiveDocument.styles.count

    For Ind = 1 To numberOfDocumentStyles
        styl = ActiveDocument.styles(Ind).NameLocal
        With ActiveDocument.Content.Find
            .ClearFormatting
            .text = ""
            .Forward = True
            .Format = True
            .Style = styl
            Do
                StyleFound = .Execute
                If StyleFound = True Then
                    ' actual code does more than alert, but keeping it simple here'
                    MsgBox styl
                    GoTo NextStyle
                Else
                    Exit Do
                End If
            Loop
        End With

    NextStyle:
        Next

End Sub   

Solution

  • I don't understand why ActiveDocument.Content is not working, but replacing it with ActiveDocument.Range(0,0) appears to resolve the issue (tested in Word 2016).

    With ActiveDocument.Range(0, 0).Find