vbams-word

Strange behavior with ActiveDocument.Paragraphs.Range


NOt an expert on VBA, but I am trying to do something very easy. I am trying to remove leading spaces from every paragraph in a Word doc.

Here is my VBA code:

Function RemoveLeadingSpaces()
    Dim apara As Paragraph

    Application.ScreenUpdating = False
    For Each apara In ActiveDocument.Paragraphs

        'apara.Range.Text = Trim(apara.Range.Text)
        Debug.Print apara.Range.Text

    Next apara
    Application.ScreenUpdating = True
End Function

The moment I uncomment the line that replaces the text I start getting some strange behavior. The loop becomes infinite and it only applies/replaces the first item/paragraph over and over. If I comment, then the debug prints all paragraphs as it should.

What am I doing wrong?


Solution

  • By adding two debugging lines, you can observe that line 5 (overwriting paragraph break) not only modifies the loop variable apara but also the Paragraph collection. On the next loop iteration, the updated first paragraph is selected again, creating an endless loop.

    Function RemoveLeadingSpaces()
        Dim apara As Paragraph
        For Each apara In ActiveDocument.Paragraphs
            apara.Range.Select ' the 1st paragraph is selected
            apara.Range.Text = Trim(apara.Range.Text)
            apara.Range.Select ' the 2nd paragraph is selected
            Debug.Print apara.Range.Text
        Next apara
    End Function
    

    enter image description here


    Please try to remove leading spaces without affecting paragraph breaks.

    btw, If the function doesn’t return a value, you can use a Sub procedure instead of a Function.

    Sub DemoRemoveLeadingSpaces()
        Dim apara As Paragraph, rngPara As Range
        Application.ScreenUpdating = False
        For Each apara In ActiveDocument.Paragraphs
            Set rngPara = apara.Range.Duplicate
            rngPara.MoveEnd wdCharacter, -1
            rngPara.Text = Trim(rngPara.Text)
            Debug.Print apara.Range.Text
        Next apara
        Application.ScreenUpdating = True
    End Sub