Search code examples
vbadocx

Clear new lines in Docx VBA


I need to delete all of new lines if is consecutive, i know macros in excel but not in word, how can i read the value of an entire line?

I read all the lines in the doc with this:

For i = 1 To 10
    Selection.MoveDown Unit:=wdLine, Count:=1
Next i

Is there other way of read each line or how to know the total lines in a word to put this in the for?

Thanks


Solution

  • I need to delete all of new lines if is consecutive

    Each blank line is actually a paragraph, so:

    Sub RemoveBlankParas()
        Dim para As Paragraph
    
        For Each para In ActiveDocument.Paragraphs
            If Len(para.Range.Text) = 1 Then
                'only the paragraph mark, so..
                para.Range.Delete
            End If
        Next para
    End Sub
    

    However, if there are only two consecutive blank paragraphs then using ReplaceAll is easier and quicker. Here's a recorded macro that can be tidied up:

    Sub Macro2()
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = "^p^p"
            .Replacement.Text = "^p"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    End Sub
    

    Word's Find/Replace feature uses a primitive form of regular expressions, so the following reduces two or more consecutive paragraph marks. NB MatchWildcards = True to use regex:

    Sub Macro2()
        Selection.Find.ClearFormatting
        Selection.Find.Replacement.ClearFormatting
        With Selection.Find
            .Text = "(^13)\1@"
            .Replacement.Text = "^p"
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchWildcards = True
        End With
        Selection.Find.Execute Replace:=wdReplaceAll
    End Sub
    

    Word regular expressions