.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

New paragraph in MS Word VBA


In a MS Word document, how can you do to create a new paragraph with a VBA? As for me, there are two simple ways.

  • Type a new paragraph from the selection: Selection.TypeParagraph
  • Find and replace any signal with a syntax ‘^p’

In this simple snippet, i focus on the second one. The main difference between the two ways is how to manipulate it. The first one is also a alternative way for the second way in case you want to perform to new a paragraph manually. The replacement using syntax you just declare it, then the script will replace it automatically once the signal is found.

ms word snippet

ms word snippet



In the snippet, you want to find for the signal ‘Gumball’ and create a new paragraph. You should do the following in your macro:

Sub FindAndReplace()
        With Selection.Find
            .Text = "Gumball"
            .Replacement.Text = "^p"
            .Forward = True
            .Wrap = wdFindContinue
        End With
        Selection.Find.Execute
End Sub

This is very simple. The question is how can we do another job for each finding. For detail, when the script locates a position of “Gumball” it will perform more than one thing which replace it with an “Enter” syntax.
If the answer is you write down the new paragraph character, then yours is wrong because the vba just understands the your “^p” syntax a simple string. It does not reflect the right thing you want it to be.
So, the resolution for this case is you will put it in a simple loop like:

Sub FindAndReplace()
        With Selection.Find
            .Text = "Gumball"
            .Replacement.Text = "^p"
            .Forward = True
            .Wrap = wdFindContinue
        End With
        Do While Selection.Find.Execute(Replace:=wdReplaceOne) = True
            Selection.MoveUp unit:=wdLine, Count:=1
        Loop
End Sub
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: