Word new line code

New paragraph / new line?

In Microsoft Word, there’s all the difference in the world between a new paragraph and a new line.

To insert a new paragraph, press the Enter key. If you have «show all characters» turned on, you’ll see each paragraph break with its «backwards P» icon. Each paragraph in Word has its own properties. It can have extra space above or below, it could be indented from the left / right margins, with the option of different indentation for the first line.

To insert a new line, press Shift + Enter. If you have «show all characters» turned on, you’ll see each manual line break with the icon of a solid arrow that goes first down, then left. Forcing a new line does not start a new paragraph, so the text will be laid out exactly as if it were a continuation of the paragraph you were in, simply on a new line. Because that’s what it is. If your paragraph has extra space above or below, this new line will simply be spaced in the same way as the line-spacing (you don’t get the extra spacing). If your paragraph has different indentation for the first line, this new line won’t have that different indentation, because it’s not the first line in a new paragraph.

That’s how you enter a line break in Word itself. But what if you want to do so in Visual Basic (i.e., in a macro)?

I needed to do this recently, and the answer was hard to find online, so I’ll write it up here — as usual, to help me find this again, and to help anyone else looking for the same thing.

New paragraphs in VBA are easy. There’s an application wide constant defined, vbCrLf, which represents ASCII character 10 (carriage return) followed by ASCII character 13 (line feed). A code snippet like this:

ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbCrLf & "Bar"

will replace the text of that paragraph with «Foo», followed by a paragraph break, followed by «Bar». Thus:

Foo and Bar in different paragraphs

But how do you get «Foo», followed by a line break, followed by «Bar», using VBA?

Foo and Bar separated by a line break

You might try some other VBA supplied constants. Such as vbCr (carriage return, ASCII 13) and vbNewLine (new line, also ASCII 13), or vbLf (line feed, ASCII 10). But all of those insert a new paragraph.

ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbCr & "Bar"
ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbLf & "Bar"
ActiveDocument.Paragraphs(6).Range.Text = "Foo" & vbNewLine & "Bar"

It turns out that what you need is ASCII 11, for which there is no pre-defined constant. The following gives you what you’re after:

ActiveDocument.Paragraphs(6).Range.Text = "Foo" & Chr(11) & "Bar"

I didn’t find that in any Microsoft documentation anywhere, but it works. Thanks for reading, and happy macro writing!

Background info

According to this answer to a question on StackOverflow, Word versions ’97-2013 used regular regexp syntax (pun intended). Unfortunately, it seems that Microsoft has since ditched regexp in favor of its own «Wildcard» syntax. I’m running Word 2016, and the only alternative to the basic literal searching (with a few special character escapes) is «Wildcard» matching, which is… basically an annoyingly limited regexp.

The answer (for those running later versions of Word)

If you’re using Word’s version of regular expression (regex/regexp) syntax (enabled by checking the box labeled «Use wildcards» in the Find and Replace dialog*), then newlines are matched by ^13 (which I suppose is equivalent to ^p, «Paragraph mark», which Find/Replace only accepts when «Use wildcards» is not selected. Go figure!).

Neither ^l («Manual line break»), ^n («Column break»), will catch regular old newlines (like, the kind you enter when you press, well, the ENTER key.

I do believe that section breaks are matched by m («Page/Section break»), however.

NB: These Replace options are not accessible via the Find interface in the Navigation sidebar that pops up when you hit CTRL+F. As user3251498 has pointed out, you must hit CTRL + H to bring up the Find and Replace dialog.

I am using openxml WordProcessingDocument to open a Word template and replace placeholder x1 with a string. This works fine unless I need the string to contain a newline.
How can I replace x1 with text may contain newlines that word would recognise? I have tried n r but these do not work

Just to explain further when the word template is opened I read it into a StreamReader then use .Replace to replace x1.

Drew Gaynor's user avatar

Drew Gaynor

8,2165 gold badges39 silver badges53 bronze badges

asked May 20, 2010 at 7:53

Danny's user avatar

2

To insert newlines, you have to add a Break instance to the Run.

Example:

run.AppendChild(new Text("Hello"));
run.AppendChild(new Break());
run.AppendChild(new Text("world"));

The XML produced will be something like:

<w:r>
  <w:t>Hello</w:t>
  <w:br/>
  <w:t>world</w:t>
</w:r>

outofmind's user avatar

outofmind

1,4001 gold badge19 silver badges36 bronze badges

answered May 20, 2010 at 8:02

codeape's user avatar

codeapecodeape

96.9k24 gold badges155 silver badges184 bronze badges

3

Here’s a C# function that will take a string, split it on line breaks and render it in OpenXML. To use, instantiate a Run and pass it into the function with a string.

void parseTextForOpenXML( Run run, string textualData )
{
    string[ ] newLineArray = { Environment.NewLine };
    string[ ] textArray = textualData.Split( newLineArray, StringSplitOptions.None );

    bool first = true;

    foreach ( string line in textArray )
    {
        if ( ! first )
        {
            run.Append( new Break( ) );
        }

        first = false;

        Text txt = new Text( );
        txt.Text = line;
        run.Append( txt );
    }

answered Oct 7, 2011 at 22:55

Toolsmythe's user avatar

ToolsmytheToolsmythe

4115 silver badges7 bronze badges

2

Altough this question is already answered I have another approach to solve questions like :

How can I make XXX with OpenXML??

In this cases you could make use of the powerful Microsoft OpenXML productivity tool (also known as OpenXmlSdkTool). Download here.

  1. Create a new office document
  2. Add the parts to the document which you would like to reproduce with OpenXML SDK.
  3. Open the office document with Microsoft OpenXML productivity tool
  4. Click on «Reflect Code»
  5. On the right side you will see now you document reflected into C# code.

Christian Junk's user avatar

answered Dec 2, 2014 at 15:54

Mischa's user avatar

MischaMischa

6356 silver badges14 bronze badges

1

I have the same issue and in my case <w:br /> tag worked.

cha0site's user avatar

cha0site

10.4k3 gold badges34 silver badges50 bronze badges

answered Mar 29, 2012 at 10:19

parm's user avatar

parmparm

1111 silver badge2 bronze badges

1

To get the tab position, you need to use wdHorizontalPositionRelativeToTextBoundary not wdHorizontalPositionRelativeToPage.

The following returns multiples of 36

Dim docrange As Range
Set docrange = ActiveDocument.Range
docrange.InsertAfter vbCr
Set docrange = ActiveDocument.Range
docrange.Collapse wdCollapseEnd
With docrange.Paragraphs(1).TabStops
.Add Position:=0, Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(0.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(1), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(1.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(2), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(2.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(3), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(3.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(4), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(4.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
.Add Position:=InchesToPoints(5.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces
End With
docrange.Paragraphs(1).Range.Select
For i = 1 To 10
‘ Insert a tab
Selection.TypeText Text:=Chr(9)
‘ Get the tab position in Points
MsgBox Selection.Information(wdHorizontalPositionRelativeToTextBoundary)
Next


Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins — Word MVP, Posted via the NNTP Bridge
«planetx» <054c912a-64ca-4426-b3da-a3e8ccc97bcd@invalid.com> wrote in message news:7bb7b9da-4957-43bf-9f60-aeb0e894dc82@communitybridge.codeplex.com…

thanks so much doug,

is there any specific reason why the code would attempt to populate this array in the manner i provided? the output of the function is… just the array!

‘ For a maximum of 10 tab stops
For i = 1 To 10

‘ Insert a tab
Selection.TypeText Text:=Chr(9)

‘ Get the tab position in pixels
iTabStops__(i) = Selection.Information(wdHorizontalPositionRelativeToPage)
Next

i still don’t get an array with values something like 36, 72, 108 etc… but get something like 108, 144 …. 72. and i’m sure its because i’m now not inserting into the range and measuring where i am in the range object after inserting each tab.

is there a reason why the entire function simply just doesn’t do:

iTabStops__(1) = InchesToPoints(0.5)
iTabStops__(2) = InchesToPoints(1)
iTabStops__(3) = InchesToPoints(1.5)
iTabStops__(4) = InchesToPoints(2)
iTabStops__(5) = InchesToPoints(2.5)
iTabStops__(6) = InchesToPoints(3)
iTabStops__(7) = InchesToPoints(3.5)
iTabStops__(8) = InchesToPoints(4)
iTabStops__(9) = InchesToPoints(4.5)
iTabStops__(10) = InchesToPoints(5)

i guess what i’m asking is… is there any situation where the following command would not place a tab stop at InchesToPoints(0.5)?

.Add Position:=InchesToPoints(0.5), Alignment:=wdAlignTabLeft, Leader:=wdTabLeaderSpaces


Doug Robbins — Word MVP dkr[atsymbol]mvps[dot]org

August 14th, 2007

Hey, Scripting Guy! Question

Hey, Scripting Guy! How can I insert a manual line break into a Microsoft Word document?

— YR

SpacerHey, Scripting Guy! AnswerScript Center

Hey, YR. Greetings (saluti) from Rome, the Eternal City! You know, according to legend, Rome was founded thousands of years ago by the twins Romulus and Remus, along with their distant cousin (and oldest living Scripting Guy) Peter Costantini. Peter, of course, denies this, inisting that he wasn’t even alive when Romulus and Remus founded the city. That might be true. If so, however, then how does he explain the shirt he always wears, the one that says “I co-founded Rome with Romulus and Remus and all I got was this stupid T-shirt”?

Interesting note. According to the Babelfish online translation service, the word Costantini, when translated from Italian to English, means “Costantini.” Strange but true!

We’ll try to figure out who really founded Rome as soon as we get the chance. Right now, however, it’s time for breakfast. So far, the Scripting Guy who writes this column has found Italian food to be quite good. After just a couple of days he’s already had, among other things:

Bigne, a pastry filled with chocolate or vanilla cream.

Napoleons, a pastry filled with both chocolate and vanilla cream.

Sfogliatelle, a pastry filled with a mandarin-flavored ricotta filling.

Pasticiotti, another pastry filled with chocolate.

Fruit tarts, éclairs, zeppole, pastiera, cassataSicilianazuppette, and profitteroli. All pastries, and all good.

Note. Is there anything to eat in Italy besides pastries? Interesting question; we’ll have to get back to you on that one, too.

In the meantime, and while we wait for our cappuccino, here’s a script that inserts a manual line break into a Microsoft Word document:

Set objWord = CreateObject(“Word.Application”)
objWord.Visible = True

Set objDoc = objWord.Documents.Add() Set objSelection = objWord.Selection

objSelection.TypeText “This paragraph is followed by a paragraph return.” objSelection.TypeParagraph()

objSelection.TypeText “This paragraph is followed by a line break.” & Chr(11)

objSelection.TypeText “This paragraph is also followed by a line break.” & Chr(11)

objSelection.TypeText “This paragraph is followed by a paragraph return.” objSelection.TypeParagraph()

Let’s explain how this script works and, along the way, show you a few pictures that should help convince you that it really does work. As you can see, we start out the way most Microsoft Word scripts start out: we create an instance of the Word.Application object and then set the Visible property to True; that gives us a running instance of Microsoft Word that we can see onscreen. Next we call the Add method in order to add a new, blank document to our instance of Word, then use the following line of code to create an instance of Word’s Selection object, something that positions the cursor at the beginning of the document and enables us to start adding text:

Set objSelection = objWord.Selection

The first bit of text we add should look relatively familiar; all we’re doing is using the TypeText method to type a sentence, then using the TypeParagraph() method to add a hard paragraph return (equivalent to pressing the ENTER key on the keyboard) at the end of that sentence:

objSelection.TypeText “This paragraph is followed by a paragraph return.”
objSelection.TypeParagraph()

Now, take a look at the next piece of text we type into our document:

objSelection.TypeText “This paragraph is followed by a line break.” & Chr(11)

Once again we’re using the TypeText method to add a sentence to the document. However, we aren’t just adding a sentence; we’re also adding Chr(11) to the end of that sentence. What’s Chr(11)? As it turns out, that’s the ASCII code for a line break. Want to add a line break to the end of a sentence in a Microsoft Word document? Then use Chr(11) rather than the TypeParagraph() method.

And then, just for heck of it, we add a couple more paragraphs, one with a line break, one with a paragraph return.

When the script finishes running our Word document will look like this:

Microsoft Word

Granted, that looks like any other Word document. But notice what happens when we click the button that shows us the formatting marks:

Microsoft Word

As you can see, lines 1 and 4 have a hard paragraph return after them; by contrast, lines 2 and 3 conclude with a soft paragraph return (a line break). If we center-align just line 2 look what happens:

Microsoft Word

Why did lines 3 and 4 also get centered? That’s easy: because they are connected using line break characters rather than paragraph returns. Proof positive that the script works!

Breaking news flash. From what we’ve just been told, Romulus and Remus did not co-found the city of Rome. According to the official story (or at least one of many official stories), the two brothers started to found the city together; however, Remus felt that Romulus was making the city walls too low. To prove his point, he proceeded to jump over the walls. Romulus, in turn, did what any self-respecting brother would do: he killed Remus, finished building the city, and then named it after himself.

Needless to say, ever since then none of his fellow Scripting Guys have been brave enough to tell Peter that he’s been building his walls too low. We’ll just have to make do with the walls the way he built them.

Like this post? Please share to your friends:
  • Word neighbours ust hk
  • Word name of time zones
  • Word neighbors ust hk
  • Word name of time zone
  • Word need for speed