Professional Documents
Culture Documents
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
PRODUCTS
SERVICES
DOWNLOADS
Categories
FORUMS
LEARNING CENTER
BLOG
BUY
SUPPORT
search
Recent Posts
SIGNIN | SITEMAP
Microsoft Word is about the authoring of documents. Documents contain pages, paragraphs, sentences and
more. Today, I want to wade into the waters of manipulating Word document content. The plan is to get
your feet wet by providing an overview of the key objects along with code samples.
Continuing the fine tradition of all Office applications (OneNote being the exception), Word has an
extensive and mature object model. My goal is to show a way to accomplish some tasks in Microsoft
Word. These samples are not necessarily, the way to do it. There is more than one way to achieve the
same results.
Today, we are concerned with the structure of a Word document not its stylings and presentation (Ill
concern ourselves with that topic next).
Word document content objects
Accessing document content objects with code
HowTo samples
Section :: Documents can contain multiple sections. This is how you apply different formatting, layout,
and header/footer options to a Word document by creating sections and formatting them differently.
Office Development
Outlook Security Manager
VDProj to WiX Converter
and WiX Designer
Video HowTo samples
List of authors
Page :: Represents a single page within a document. A page can reside within a Range.
Paragraph :: A single paragraph of content. A paragraph can reside within a Selection, Document, or
Range and is accessible via the Paragraphs collection object. Paragraphs also contain the formatting for
content residing above it. Dont ponder over that last sentence too much, I will explain it further in my
next article.
Sentence :: This object does not exist strange as that might seem. Instead, there is the Paragraphs
collection object. This collection contains a collection of Range objects, which in turn, contain all the
sentences for the Range. Confused? The code samples will help bring focus to the picture.
Eugene Starostin
Selection :: This object contains the content selected either by the user or via code. It also is the
insertion point if no selection exists. The insertion point is where the cursor blinks in the Word UI to
inform the user of their location within the document.
Andrei Smolin
Range :: Think of this object like realestate. It contains a contiguous section of a document. Perhaps its
Eugene Astafiev
two most popular properties are Start and End. They contain ranges starting and ending character
positions within the Word document.
Dmitry Kostochko
Fokke Post
There are more content objects than these but the list above are the major objects that provide access
to everything else.
Sergey Grischenko
Renat Tlebaldziyeu
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
1/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
I want to give you a lot of VB.NET code samples today. Ill start with the Range object and keep going as
long as I have paper. By the end of the samples, my hope is you will have a general idea of how to access
and edit content within a Word document.
Tags
This method loops through all the paragraphs in the active document and reverses their order in a new
document.
C# COM add
ins CommandBars
Delphi
Deployment
addons
MAPI Object
model Office
Office 365
Office 2013 Office
Outlook
2016
Outlook regions
Outlook security PIAs
PowerPoint Project
Ribbon RTD
servers
SharePoint smart
tags
task panes
Visual Studio
VSTO WiX Word
XLL
PrivateSubEnumerateParagraphs()
DimcurDocAsWord.Document=WordApp.ActiveDocument
DimnewDocAsWord.Document
DimrngAsWord.Range
DimstrAsString=""
DimiAsInteger
rng=curDoc.Content
i=rng.Paragraphs.Count()
DoUntili=0
str=str&rng.Paragraphs.Item(i).Range.Text&vbCrLf
i=i1
Loop
newDoc=WordApp.Documents.Add
newDoc.Range().Text=str
Marshal.ReleaseComObject(rng)
Marshal.ReleaseComObject(curDoc)
Marshal.ReleaseComObject(newDoc)
The key is the use of the Range object and all the document content. The code first grabs all the
document content and assigns it to a Range variable (rng). Then the code finds out how many paragraphs
exist and loops backwards to create a string. This string is then inserted into a new document. Its a good
bar trick that only works in nerd bars.
curDoc.Bookmarks("\page").Range.Select()
Marshal.ReleaseComObject(curDoc)
EndSub
In this procedure, I employ the predefined page bookmark. This is a standard Word bookmark that always
exists and allows easy selection of the page containing the current focus (or selection).
You can learn more about predefined bookmarks at MSDN.
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
2/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
DimstrAsString=""
DimiAsInteger
rng=curDoc.Content
i=rng.Sentences.Count()
DoUntili=0
str=str&rng.Sentences.Item(i).Text
i=i1
Loop
newDoc=WordApp.Documents.Add
newDoc.Range().Text=str.ToUpper
Marshal.ReleaseComObject(rng)
Marshal.ReleaseComObject(curDoc)
Marshal.ReleaseComObject(newDoc)
EndSub
To mix it up, the final documents text is upper case. I know, this is dazzling trickery.
The takeaway is that the Range object contains a section of the Word document. Within it are major items
like paragraphs and sentences.
Enumerate sections
You can loop through document sections by accessing the Sections collection. This collection resides
directly beneath the Document object.
PrivateSubEnumerateSections()
DimcurDocAsWord.Document
DimnewDocAsWord.Document
DimstrAsString=""
DimiAsInteger
curDoc=WordApp.ActiveDocument
Fori=1TocurDoc.Sections.Count
str=str&"SECTION"&i&vbCr
str=str&vbTab&"start="&curDoc.Sections(i).Range.Start
str=str&vbTab&"end="&curDoc.Sections(i).Range.End&vbCrLf
Next
newDoc=WordApp.Documents.Add
newDoc.Range().Text=str
Marshal.ReleaseComObject(curDoc)
Marshal.ReleaseComObject(newDoc)
EndSub
This procedure builds a string that 1) lists each document section and 2) contains the sections Start and
End character position. Notice the use of the Range object to read this information.
curDoc.Sections.Add(WordApp.Selection.Range)
Marshal.ReleaseComObject(curDoc)
EndSub
This sample inserts a section break at the current selection (or cursor) location. Again, notice the use of
the Range property. You can easily grab a different range within the document and pass it as the location
of the page break.
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
3/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
Enumerate pages
Someday you might want to loop through all document pages and perform some very specific business logic
on them. This code does exactly that.
PrivateSubEnumeratePages()
DimcurDocAsWord.Document
DimnewDocAsWord.Document
DimpgsAsWord.Pages
DimstrAsString=""
DimiAsInteger
curDoc=WordApp.ActiveDocument
pgs=curDoc.ActiveWindow.Panes(1).Pages
Fori=1Topgs.Count
str="PAGE"&i&vbCr
str=str&vbTab&"height="&pgs.Item(i).Height
str=str&vbTab&"width="&pgs.Item(i).Width&vbCrLf
Next
newDoc=WordApp.Documents.Add
newDoc.Range().Text=str
Marshal.ReleaseComObject(pgs)
Marshal.ReleaseComObject(curDoc)
Marshal.ReleaseComObject(newDoc)
EndSub
Here, the business logic is to create a string that contains the height and width of each page and then
display it in a new document. Your business logic will probably be more complex than this. Consider this
procedure a starter kit for processing document pages.
sel.InsertBreak(Type:=Word.WdBreakType.wdPageBreak)
Marshal.ReleaseComObject(sel)
EndSub
I start by referencing the current insertion point via the Selection object. I then invoke the InsertBreak
method and specify a page break. Walla! We have a new page.
Insert a table
I use tables all the time. I can see how it would be useful to have a procedure that inserts a table exactly
how I like it.
PrivateSubInsertTable(rowCountAsInteger,columnCountAsInteger)
DimcurDocAsWord.Document=WordApp.ActiveDocument
DimtableAsWord.Table
table=curDoc.Tables.Add(WordApp.Selection.Range,rowCount,columnCount)
table.Cell(1,1).Range.Text="HelloTable"
Marshal.ReleaseComObject(table)
Marshal.ReleaseComObject(curDoc)
EndSub
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
4/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
In this case, I like a table with 1 column and 7 rows and 0 formatting. The Tables collection resides under
the Document object. To add a new table, you call the collections Add method and specify its location
(via a Range object), number of rows, and number of columns.
Enumerate comments
Authoring a quality document of any type (blog, article, report, proposal, etc.) is a collaborative effort.
Comments are key to the collaborative process. If you receive your document after this process and it is
littered with helpful comments for improving it the following code will come in handy.
PrivateSubEnumerateComments()
DimcurDocAsWord.Document=WordApp.ActiveDocument
Fori=1TocurDoc.Comments.Count
curDoc.Comments.Item(i).Range.Text=_
curDoc.Comments.Item(i).Range.Text&vbCrLf&_
"Corrected.It'sallgoodnow!"
Next
Marshal.ReleaseComObject(curDoc)
EndSub
Here, I loop through the Comments collection. This collection also resides directly under the Document
object. For each comment, I insert a comment below the existing comment text.
Create a comment
Creating a comment is straightforward. The approach below utilizes the current selections range as the
insertion point.
PrivateSubCreateComment(commentTextAsString)
WordApp.Selection.Comments.Add(WordApp.Selection.Range,commentText)
EndSub
The text for the comment needs to be passed as the procedures parameter.
You can also create comments by calling Document.Comments.Add. If you do that, you need to pass a
Range to specify where to insert the comment.
curDoc.DeleteAllComments()
Marshal.ReleaseComObject(curDoc)
EndSub
Insert text
To insert text, you can utilize the Selection and Range objects.
PrivateSubInsertText(textToInsertAsString)
WordApp.Selection.InsertAfter(textToInsert)
'WordApp.Selection.InsertBefore(textToInsert)
'WordApp.ActiveDocument.Range.InsertAfter(textToInsert)
EndSub
In this sample, I utilize the current selection to insert the passed string after the current selection. Ive
include commented code to show how you can chose to InsertBefore. Also, Ive shown how to do the same
with the Range object.
Find text
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
5/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
Finding text is a core competency in Word solution development. This sample performs search and replace.
PrivateSubFindText()
DimrngAsWord.Range
rng=WordApp.ActiveDocument.Content
Withrng.Find
.ClearFormatting()
.Execute(FindText:="HelloTable",_
ReplaceWith:="FoundTable",_
Replace:=Word.WdReplace.wdReplaceAll)
EndWith
Marshal.ReleaseComObject(rng)
EndSub
The procedure sets a Range object that contains all document Content. It then executes a Find & Replace
action to replace the text inserted in the InsertTable method from earlier.
Marshal.ReleaseComObject(rng)
Marshal.ReleaseComObject(curDoc)
EndSub
This method stores the first 3 paragraphs in a Range object, copies them, moves to the end of the
document, and pastes the paragraphs. Ive included commented code that shows how you could perform
the copy using a Selection object.
***
We have now delved into the waters of Word document content manipulation. Well continue looking at
scenarios in future articles!
Available downloads:
This sample Word addin was developed using Addin Express for Office and .net:
VB.NET Word Document Content addin
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
6/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
Part 11: Populating Word documents with data from external sources
Part 12: Working with Microsoft Word templates
.NET , VB.NET , Word
Filed under Addin Express for Office and .net , HowTo samples
23 Comments
Ron
November 15, 2013 at 9:55 am
Hello Ron,
According to MSDN, the HeadersFooters collection does not have the Text property:
http://msdn.microsoft.com/enus/library/office/ff197925.aspx
So, I cannot figure out how your code works.
Shai
December 6, 2013 at 8:47 am
Thanks for the post and really been helpful. I wonder how can I delete a page from a word doc. for example I want
to delete page #3 from a 5 page document. I am populating data on a word template. Every page has a picture and
some statements and putting data from different database tables. But in case there is no data in a particular page
because the underlying database table has no record of it, want to delete that page. I know which page to delete
but do not know how to delete. Please help.
Ty Anderson
December 6, 2013 at 5:30 pm
Hello Shai!
You want to use the Range object.
First navigate to the page you want to delete using the GoTo command.
Then set a Range to reference the entire page.
Last, delete it by calling Range.Delete.
Here is some code that can get you started.
With WordApp.ActiveDocument
Set Rng = .GoTo(What:=wdGoToPage, Name:=iPage)
Set Rng = Rng.GoTo(What:=wdGoToBookmark, Name:=\page)
Rng.Delete
End With
You can check if the page is blank by checking the ranges Word count.
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
7/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
If Rng.Words.Count = 0 then Rng.Delete
Good luck.
Ty
Dustin C.
December 18, 2013 at 9:34 pm
Quick question: I consistently have reports that are actually aggregates of individual reports. This is outside of my
control (right now), but I would like to break them up into their individual documents through some of the methods
you listed above. One nice part is that the individual reports consistently have END OF REPORT near the end of
the document (two lines above the end of the page, to be specific). My thought was to try to key off of that phrase,
somehow drop the cursor down, and split the documents off that way. As I am somewhat of a novice to these
objects, I was wondering if you could maybe shed some light?
Thanks,
Dustin
Hello Dustin,
The best way is to record a VBA macro while performing the actions in the Word UI that you need your addin to
perform. Start with searching the END OF REPORT string, then select the report, cut it, create a new document,
paste the contents, etc. The point is: the recorded macro shows the members of the Word object model involved in
the process. Then youll be able to convert the macro to the programming language that you use. While working on
this, you may find useful to look into the Reference and Concepts sections at http://msdn.microsoft.com/en
us/library/office/ee861527.aspx.
Ty Anderson
December 27, 2013 at 3:14 pm
Hi Dustin,
I did a little bit of research and found this article:
How to programmatically save each page or section of a document as a separate file
I think the samples it provides will serve as a good start.
You have two options here
1 Prepare the document by manually inserting sections after the END OF REPORT line.
2 Use the Word object model to scan each page to locate END OF REPORT. When you find it, use the Selection
object to include all content above END OF REPORT, select it, and save it.
Good luck,
Ty
Victor
April 4, 2014 at 1:13 am
Hi Anderson,
Thank you for porting this ,its really usefull to me. And i have a problem to binding data using Xml Mapping
custom xml nodes .
I have template in that i added custom xml nodes, and i bind the data based on Xml nodes using vb.net . like below
For Each XMlnode As Word.ContentControl In wordDoc.ContentControls
If XMlnode.XMLMapping.CustomXMLNode.BaseName = Desc Then
OperList.Add(XMlnode.XMLMapping.CustomXMLNode.BaseName)
Next
wordDoc.ActiveWindow.Selection.InsertRowsBelow()
when i try to insert new row in a table using above line command ,it is insert but xmlnodes not carried to new row
How can i approach to print data in multiple row using xml nodes .
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
8/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
please help me ..
Thank you .
Ty Anderson
April 8, 2014 at 12:12 am
Hi Victor,
Thanks for raising this question.
Please allow me a couple of days to respond.
Ty
Victor
April 10, 2014 at 12:43 am
Hi Anderson ,
Thank you for giving response to my problem.
i will wait for your answer
Thank you .
Ty Anderson
April 16, 2014 at 12:14 am
Victor,
What version of Word are you targeting?
Also, can you send your code and document to me to look at further?
What you are doing makes sense but I need more context.
Are you trying to create repeating content controls in a pre Word 2013 version of Word? See below:
Repeating section content controls represented in the object model
Kavitha
April 23, 2014 at 10:27 am
Hi Ty Anderson,
I am struct at repeating data in word 2013.
can you please find my word document at below link:
https://onedrive.live.com/redir?resid=D935E20D58C2FDAF%21107
and XML file : https://onedrive.live.com/redir?
resid=D935E20D58C2FDAF!112&authkey=!ACL29rLRh6Yg0lA&ithint=file%2c.XML
In word document CARRIER INFORMATION section i have to loop the data. But first row only it is printing.in second
row i dont have the xml nodes.so it is not printing.
But i need to print all lines in CARRIER INFORMATION.
Let me know how can i print all lines.
Kavitha
April 24, 2014 at 2:25 am
Hi Ty Anderson,
Can i have samples of using Repeating section content controls in VB.Net.
i have find related code in VBA
http://gregmaxey.mvps.org/word_tip_pages/contentcontrol_enhancements_word_2013.html
I have one more doubt. I have word document template with office 2013.If i give this to customer who is using
office 2010. how then cam manage custom xml nodes.
Ty Anderson
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
9/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
April 29, 2014 at 8:46 am
Hi Kavitha
Thank you for the sample code. I will take a look.
Ty
Ty Anderson
May 7, 2014 at 6:30 am
Hi Kavitha,
I reviewed your document and I think you need to look at how you setup the repeating content controls in the
document. I dont see a repeating section content control in the Bill of Lading document.
Please review these articles:
http://www.techrepublic.com/article/protipnestcontentcontrolsusingword2013snewrepeatingsection
contentcontrol/#.
http://msdn.microsoft.com/enus/library/office/jj889465(v=office.15).aspx
For a code sample, this might help:
http://social.msdn.microsoft.com/Forums/enUS/4e9fd33fb13a4a7d90b948a96a33a71e/howcaniloopthe
repeatingsectioncontentcontrolsusingvbnet?forum=worddev
Ty
Charles Hurst
June 4, 2014 at 2:21 am
Hi Ty,
Thanks for the post it was an insightful read on my current project.
Im having one issue where by my code is currently stripping out any Header content and replacing with whatever
the user selects from my Pop up.
Is there anyway to insert text in to Word Header with a merge (preferably on top) without deleting all current
content?
Thanks in advance,
Charles
Hi Charles,
Yes, it is possible. Please have a look at the following MSDN article:
http://msdn.microsoft.com/enus/library/ms178795.aspx
It demonstrates how to get a Range object of the main Header. Using the Range object you will be able to get and
set its Text.
Ajith. S
December 9, 2014 at 5:21 am
Hi Anderson
Your article on Working with Word document content objects is very informative.
My concern is programmatically using Inter.Word library how can i enable a search.
The search results should be displayed in the navigation pane, showing all the details of the matches found.
Kindly help.
Thanks in advance
Ty Anderson
December 10, 2014 at 6:04 pm
Hello Ajith
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
10/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
Unfortunately, Word does not provide an API object for the Navigation pane.
It is possible however to build your own pane that mimics the search behavior you want to automate.
You can execute searches using the Find object:
http://msdn.microsoft.com/enus/library/office/ff839118(v=office.15).aspx
Ty
Vijay Nanda
February 14, 2015 at 3:31 pm
Hi Anderson,
I want to write a small programme using VB 6.0 and MS Word 2007 wherein I want to create a document (My
Report.doc) which can be edited, reformatted, displayed and printed. The full details are as under:
There are 12 conditions. if condition No. 1 is met some prebookmarked portion from the already existed MS Word
File (C:\My File.doc) is to be copied, a New Word Document is opened with the name My Report.doc and the
copied portion is pasted on it.
For example,
If K = 1 Then (read pre bookmarked portion from the World File (C:\My File.doc) Open a New Word Document and
copy paste the selected portion in this New Word Document (My Report.doc).
Elseif K = 2
Then (read selected portion from the World File (C:\My File.doc) Open a New Word Document and copy paste the
selected portion in this New Word Document (My Report.doc).
and so on till K = 12 is tested. (Only one option will be true hence only one MS Word File (My Report.doc) will be
Opened.
Similarly L, M, N, O, P, Q, R,S & T are to be tested (12 Times each) and the entire information is to be deposited in
one single MS Word File (My Report.doc).
Note :
(Text in the C:\My File is simple text divided into paragraphs. There are no Tables/Fields etc.)
I shall be grateful, if you could help me in making this programme using VB 6.0 and MS Word 2007 for my personal
use.
With Kind Regards
Vijay Nanda
Ty Anderson
February 18, 2015 at 10:23 pm
Hello Vijay,
I cant help you write the app with VB6 but I can point you to some useful links:
http://word.mvps.org/faqs/macrosvba/WorkWithBookmarks.htm
http://www.vbexplorer.com/VBExplorer/office_vb.asp
Is VB6 a strict requirement? If so, why?
Ty
Ravikumar
May 10, 2015 at 11:49 am
Hi,
how to get the total count of characters from beginning of the document to the current cursor position. i want to
get total characters from starting to cursor edit point, not the total characters in the document.
Please help
Thanks.
Ty Anderson
May 12, 2015 at 12:59 pm
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
11/12
7/17/2015
WorkingwithWorddocumentcontentobjectsVB.NETcodesamples
Hi Ravikumar,
To count the characters is simple. You only need to check this:
Dim currentPosition As Long
currentPosition = Selection.Range.Start
The Selection.Range.Start is the position of the cursor.
The integer value that .Start returns, is the number of characters that precedes it within the document.
I hope this helps.
Ty
Post a comment
Name
Email address (will not be published)
Website
SubmitComment
Website
Developer Guides
Links
Samples
Microsoft and the Office logo are trademarks or registered trademarks of Microsoft
Corporation in the United States and/or other countries. All other trademarks are
property of their respective owners.
https://www.addinexpress.com/creatingaddinsblog/2013/08/07/worddocumentcontentobjects/
12/12