Creating multiple Word paragraphs with Document.Paragraphs.Add() - vba

I'm using a macro in Excel to add information to a Word document. I'm trying to add 10 lines to an existing Word document like this:
Sub AddParagraphs()
'Open Word
Dim wordApp As Word.Application
Set wordApp = CreateObject("Word.Application")
'Open
Dim doc As Word.document
Set doc = wordApp.Documents.Open("c:\temp\document.docx")
'Add 10 paragraphs
Dim idx As Integer
For idx = 1 To 10
Dim paragraph As Word.paragraph
Set paragraph = doc.Paragraphs.Add()
paragraph.Range.style = wdStyleHeading2
paragraph.Range.text = "Paragraph " & CStr(idx)
Next
doc.Save
doc.Close
wordApp.Quit
End Sub
I have an empty Word document at C:\temp\document.docs but after running the code there is only one line with the text "Paragraph 10". I was expecting 10 lines.
As far as I can tell the Paragraphs.Add() with no arguments should create a new paragraph. Perhaps I'm mistaken to believe that a new paragraph produces a new line? Is there another way to add 10 lines in a loop where each can have a specific (not the same) style?

The "paragraph" that you are adding does not have a paragraph mark at the end.
Change that line to
paragraph.Range.Text = "Paragraph " & CStr(idx) & vbCr
and that should fix your problem.

Actually, what's happening in the original code is that you're always replacing the content when you use
Doc.Paragraphs.Add
So there's only ever the one paragraph. There are various ways to get around this. One is to use InsertAfter, as has been mentioned in comments. (Note that if you're going to use this, the correct way to specify a new paragraph as part of a string is vbCr or Chr(13). Word can very easily misinterpret anything else!)
My personal preference is to work with a Range object that can be manipulated independently of the entire document. For example, it can be done like this:
Sub AddParagraphs()
'Open Word
Dim wordApp As Word.Application
Set wordApp = CreateObject("Word.Application")
'Open
Dim doc As Word.document
Set doc = wordApp.Documents.Open("c:\temp\document.docx")
Dim rng as Word.Range
Set rng = doc.Content
'Add 10 paragraphs
Dim idx As Integer
For idx = 1 To 10
Dim paragraph As Word.paragraph
'So that the next thing inserted follows instead of replaces
rng.Collapse wdCollapseEnd
Set paragraph = rng.Paragraphs.Add
paragraph.Range.style = wdStyleHeading2
paragraph.Range.text = "Paragraph " & CStr(idx)
Next
doc.Save
doc.Close
wordApp.Quit
End Sub

I had a similar problem. Adding doc.Range.InsertParagraphAfter fixed my problems. The following code should work for you:
Sub AddParagraphs()
'Open Word
Dim wordApp As Word.Application
Set wordApp = CreateObject("Word.Application")
'Open
Dim doc As Word.document
Set doc = wordApp.Documents.Open("c:\temp\document.docx")
'Add 10 paragraphs
Dim idx As Integer
For idx = 1 To 10
Dim paragraph As Word.paragraph
Set paragraph = doc.Paragraphs.Add()
paragraph.Range.style = wdStyleHeading2
paragraph.Range.text = "Paragraph "
doc.Range.InsertParagraphAfter
Next
doc.Save
doc.Close
wordApp.Quit
End Sub

The Paragraphs.Add method appends a new paragraph consisting of the paragraph mark only at the end of the document. Oddly enough, the return value is not the now last paragraph but the penultimate paragraph. You get a reference to the new last paragraph by the Next method of the paragraph object. You can then set the style and insert text with the paragraph.Range.InsertBefore method.
The critical part of your code must be like this
'Add 10 paragraphs
Dim idx As Integer
Dim paragraph As word.paragraph
For idx = 1 To 10
Set paragraph = doc.Paragraphs.Add.Next
paragraph.Range.style = word.WdBuiltinStyle.wdStyleHeading2
paragraph.Range.InsertBefore "Paragraph " & CStr(idx)
Next

Related

How do I add a bookmark within the body of a Word doc using interop

I have a template document which contains a number of bookmarks used thus;
mDoc.Bookmarks(bookmark).Range.Text = "My test".
I would now like to add a new bookmark at the position in the doc at the end of the string "My test" but cannot find any guidance on how to specify the range in;
Dim Bookmarks As Word.Bookmarks
Dim myBookmark As Word.Bookmark
Dim bookmarkRange As Word.Range
Dim Selection As Word.Selection
'doc = mWord.ActiveDocument
Selection = mWord.Selection
bookmarkRange = Selection.Range
Bookmarks = mDoc.Bookmarks
myBookmark = Bookmarks.Add("MyBookmark", bookmarkRange) 'this works but puts it at the start of the doc
mDoc.Bookmarks("MyBookmark").Range.Text = "text inserted at MyBookmark"
How would I do that?
Your existing code does not add text to the bookmarked range; it inserts that text after the bookmark. To add text to a bookmarked range, use something like the following VBA code:
Dim BkMkRng As Range
With ActiveDocument
If .Bookmarks.Exists("MyBookmark") Then
Set BkMkRng = .Bookmarks("MyBookmark").Range
BkMkRng.Text = "My Text"
.Bookmarks.Add "MyBookmark", BkMkRng
End If
End With
To insert an new bookmark after that range, simply use something along the lines of:
With ActiveDocument
If .Bookmarks.Exists("MyBookmark") Then
Set BkMkRng = .Bookmarks("MyBookmark").Range
BkMkRng.Collapse wdCollapseEnd
BkMkRng.Text = "My New Text"
.Bookmarks.Add "MyNewBookmark", BkMkRng
End If
End With
From where you are, you could replace
mDoc.Bookmarks("MyBookmark").Range.Text = "text inserted at MyBookmark"
with
Dim myRange As Word.Range
myRange = mDoc.Bookmarks(myBookmark).Range
myRange.Text = "text inserted at MyBookmark"
myRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd)
myRange.Bookmarks.Add("MyNewBookmark")

VBA Turn .selection from Word Document into a string

Good Evening. I've been trying to transform a whole Word doc into a string. My current problem is that I can open the doc, select the text, but I can't manage to transform into a string. Funny thing is that a msgbox print the text on the screen.
Dim s_txt as string
Dim wrdDoc As Word.Document
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
s_arq = Cells(1, i_col)
Set wrdDoc = wrdApp.Documents.Open("C:\Users\USER\Desktop\TCC\pdf2doc\" & s_arq)
wrdApp.Selection.WholeStory
wrdApp.Selection.Find.ClearFormatting
MsgBox(wrdApp.Selection)
s_txt = wrdApp.Selection
wrdApp.Quit
When I try to get the string s_txt it returns nothing. But the msgbox print the text perfectly.
I tried selection.text, and it returns nothing.

How to write two equations in different lines in word from vb.net

Am working on automating a word document from VB.net and am unable to write an equation in a separate two different lines. The code I have is here, it will write the equations in single line (merged in one), but I want them in different lines please help.
am using word 2016 and vb.net 2017
Imports Microsoft.Office.Interop.Word
'**************Intializing Word Document****************************
Dim oWord As Microsoft.Office.Interop.Word.Application
Dim oDoc As Microsoft.Office.Interop.Word.Document
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
'*******************************************************************
'**************************eq 1*****************************************
Dim objRange As Range
Dim objEq As OMath
objRange = oDoc.Bookmarks.Item("\endofdoc").Range
objRange.InsertParagraphAfter()
objRange.Text = "σ_1 (L_x/2,L_y/2)=N_sd/(L_x L_y )+(M_x (L_y/2))/I_x +(M_y (L_x/2))/I_y = "
objRange = oDoc.OMaths.Add(objRange)
objEq = objRange.OMaths(1)
objEq.BuildUp()
'**************************eq 2*****************************************
Dim objRange1 As Range
Dim objEq1 As OMath
objRange1 = oDoc.Bookmarks.Item("\endofdoc").Range
objRange1.InsertParagraphAfter()
objRange1.Text = "σ_2 (L_x/2,L_y/2)=N_sd/(L_x L_y )+(M_x (L_y/2))/I_x +(M_y (L_x/2))/I_y = "
objRange1 = oDoc.OMaths.Add(objRange1)
objEq1 = objRange1.OMaths(1)
objEq1.BuildUp()
The problem is a slight mismanagement of the ranges and oMaths collection. You don't need a second range, just need to shift the first one. After you set the range's initial position, just enter the equation on the first line. Then, you insert a paragraph and call insertafter to add another equation to the document. Insertafter will automatically set the range's value to the newly added text. Then simply add that second range to the omaths collection, making its count 2. Finally, call buildup on the entire collection and it will build both equations.
With those changes applied, you get the following code which produces two equations on different lines:
'**************Intializing Word Document****************************
Dim oWord As Microsoft.Office.Interop.Word.Application
Dim oDoc As Microsoft.Office.Interop.Word.Document
'Start Word and open the document template.
oWord = CreateObject("Word.Application")
oWord.Visible = True
oDoc = oWord.Documents.Add
'**************************eq 1*****************************************
Dim objRange As Range
objRange = oDoc.Bookmarks.Item("\endofdoc").Range
objRange.Text = "σ_1 (L_x/2,L_y/2)=N_sd/(L_x L_y )+(M_x (L_y/2))/I_x +(M_y (L_x/2))/I_y = "
objRange = oDoc.OMaths.Add(objRange)
'**************************eq 2*****************************************
objRange = oDoc.Bookmarks.Item("\endofdoc").Range
objRange.InsertParagraphAfter()
objRange.InsertAfter("σ_2 (L_x/2,L_y/2)=N_sd/(L_x L_y )+(M_x (L_y/2))/I_x +(M_y (L_x/2))/I_y = ")
objRange = oDoc.OMaths.Add(objRange)
objRange.OMaths.BuildUp()

Getting to the top of a word document in VB.net [duplicate]

This question already has answers here:
Position cursor at start/end of Word document
(9 answers)
Closed 6 years ago.
I am opening a word document from my VB windows forms application then adding text from several text boxes. I need this text to go to very beginning of the document every time rather than at the very end. Have searched online for hours and cannot seem to find a solution to this! I have managed to find WdGoToDirection.wdGoToFirst but don't know what to do with it. Any guidance would be a help.
Dim oWordApp As New Word.Application
oWordApp.Visible = True
Dim oDoc As Word.Document = oWordApp.Documents.Open("C:\Users\christopherm\Desktop\TestBoard.htm")
oDoc = oWordApp.ActiveDocument
Dim oPara1 As Word.Paragraph, oPara2 As Word.Paragraph
Dim oPara3 As Word.Paragraph, oPara4 As Word.Paragraph
Dim oBeginning As Object = WdGoToDirection.wdGoToFirst
oPara1 = oDoc.Content.Paragraphs.Add
oPara1.Range.Text = "Heading 1234" & vbCrLf
oPara1.Format.SpaceAfter = 0
oPara1.Range.Font.Bold = True
oPara1.Range.Font.Size = 12
oPara1.Range.Font.Name = "Calibri"
oPara1.Range.InsertParagraphAfter()
You need to get a Range object that points to the beginning of the document. You can get that by getting the entire range of the document and then going to the beginning of that range:
Dim rng as Range = ActiveDocument.Range
rng.Collapse ' collapses the range to the beginning
rng.Text = "Heading 1234" & vbCrLf
Dim para1 as Paragraph = rng.Paragraphs(1)
para1.Format.SpaceAfter = 0
' continue here ...
If you instead want to use the Document.Paragraphs.Add method to insert a new paragraph at the beginning of the document, you need to pass a range object pointing to that location:
Dim rng As Range = ActiveDocument.Range
rng.Collapse ' range object at the beginning of the document
' pass the range where the paragraph shall be inserted
Dim para1 as Paragraph = ActiveDocument.Paragraphs.Add(rng)

Delete everything except the first word in every paragraph

I have a long list of Accounts labels which I need to format out the contact information to leave only the name (first word in every paragraph). I have some experience with VBA excel, but this is my first foray into word.
So what I want to do is delete everything after the first word, but leave all paragraph breaks intact, if possible (whoever made the list formatted it with lots of breaks, rather than spacing).
Thanks a ton in advance!
Try something like this, modify as needed. Not 100% sure it will preserve your paragraph breaks but this should at least get you to a list of "first word" in each of the paragraphs.
Sub FirstWord()
Dim myString$
Dim MyDoc As Document
Dim DocPara As Paragraph
Dim i%
Dim p%
Set MyDoc = ActiveDocument
For p = MyDoc.Paragraphs.Count To 1 Step -1
Set DocPara = MyDoc.Paragraphs(p)
i = InStr(1, DocPara.Range.Text, " ")
DocPara.Range.Text = _
Left(DocPara.Range.Text, i) & Right(DocPara.Range.Text, 1)
Next
End Sub
UPDATED
To address leading spaces indenting each paragraph, try this instead. I'm going to modify the above routine so you can see a few changes to this code and how I just adapt it. I haven't tested this version yet, letme know if any problems.
Sub FirstWordIndented()
Dim myString$
Dim x% '<-- this is new
Dim MyDoc As Document
Dim DocPara As Paragraph
Dim i%
Dim p%
Set MyDoc = ActiveDocument
For p = MyDoc.Paragraphs.Count To 1 Step -1
Set DocPara = MyDoc.Paragraphs(p)
'// Make sure to ignore leading spaces
'// This block should remove leading spaces
myString = DocPara.Range.Text
Do
If Not Left(myString,1) = " " Then Exit Do
'// Removes the first character if it's a space
myString = Right(myString, Len(myString) - 1)
'// Loop until the first character isn't a space
Loop
'// Some small modifications to use the myString variable in this block:
i = InStr(1, myString, " ")
DocPara.Range.Text = _
Left(myString, i) & Right(myString, 1)
Next
End Sub
BEFORE
AFTER