Friday, March 14, 2014

How to Delete empty paragraph and format within word document with word vba

Leave a Comment


Suppose that you want remove unwanted empty paragraphs within your word document, the following code snippet will show how that you can remove those empty paragraph.

What is empty paragraph?
It is a blank line that exists in the word document.

How to delete
In order to delete the empty paragraph from your word document, iterate all the paragraph with your document with ActiveDocument.Paragraphs and Check word count between 1 and 0.



Full Code
PublicSub DeleteEmptyParagraph()
    Dimi, iSpace, iCounter As Integer
    DimsSpace As Single
    Dimopara As Paragraph
   
    ' Calculate and Delete Empty paragraph
    sSpace = iSpace = 0
    ForEach opara In ActiveDocument.Paragraphs
        Ifopara.Range.Words.Count <= 1 And opara.Range.Words.Count > 0 Then
            opara.Range.Delete
            iSpace = iSpace + 12
        Else
            sSpace = iSpace + opara.SpaceBefore
            opara.SpaceBefore = sSpace
            iSpace = 0
        End If
       
        'Add empty Paraagraph
        sSpace = opara.SpaceBefore
        opara.SpaceBefore = 0
        IfsSpace >= 4 And sSpace <= 7.5 Then
            opara.SpaceBefore = 5
        ElseIfsSpace > 7.5 And sSpace < 20 Then
            ActiveDocument.Paragraphs.Add Range:=opara.Range
        ElseIfsSpace >= 20 Then
            ActiveDocument.Paragraphs.Add Range:=opara.Range
            ActiveDocument.Paragraphs.Add Range:=opara.Range
        End If
       
    Next opara
      
   ' Format Empty Paragraph
    Selection.HomeKey
    Selection.WholeStory
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Font.Size = 12
    WithSelection.Find
        .Text = "^p"
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    EndWith
    Selection.Find.Execute Replace:=wdReplaceAll
   
Set opara = Nothing
EndSub

0 comments :

Post a Comment

DMCA.com Protection Status