Blue Theme Orange Theme Green Theme Red Theme
 
Mindcracker MVP Summit 2012
Home | Forums | Videos | Photos | Blogs | Beginners | Advertise with Us
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Mindcracker MVP Summit 2012
Search :       Advanced Search »
Home » Office and VB.NET » Creating and opening Microsoft Word document from VB.NET

Creating and opening Microsoft Word document from VB.NET

This article is being written in response to a couple inquiries on the question, "How do I open a word document from .NET?". I guess after people read my excel article, they were under the impression that I knew how to do this in Word. Luckily, after some hunting around on the forums and feedback from other C# Corner members I got the gist of it.

Author Rank :
Page Views : 269356
Downloads : 3754
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
WordFromDotNet.zip
 
 
Discover the top 5 tips for understanding .NET Interop
Become a Sponsor
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 



WordInterop.jpg




Figure 1 - Word Launched from .NET Form

This article is being written in response to a couple inquiries on the question, "How do I open a word document from .NET?".    I guess after people read my excel article, they were under the impression that I knew how to do this in Word.  Luckily, after some hunting around on the forums and feedback from other C# Corner members I got the gist of it.

The First Step in manipulating Word in .NET is that you'll need to add a COM reference to your project by right clicking in the solution explorer on References->Add Reference.  Click on the COM tab and look for the Microsoft Word 9.0 Object Library.  Click Select and OK.

ChoosingWordCOM.jpg

Figure 2 - Adding a Word COM Reference to your .NET Project

The code above opens a document based on the file chosen in the OpenFileDialog.  Notice the parameters passed to the Document.Open method are all references.  Don't ask me why it was done this way, but it seems like when Microsoft goes through a call with optional parameters, they had no choice but to make everything a variant so on the C# side of the parameter list looks like a bunch of references to objects.  If you want to skip over a parameter in the call to Open, use the System.Reflection.Missing.Value and assign it to an object.  Once you know this trick, the rest of the interoperability used with Word is pretty straightforward.
Below is the code for creating a document from scratch:

Private Sub button1_Click(ByVal sender As Object, ByVal e As System.EventArgs)
' Use the open file dialog to choose a word document
If Me.openFileDialog1.ShowDialog() = DialogResult.OK Then
' set the file name from the open file dialog
Dim fileName As Object = openFileDialog1.FileName
Dim readOnly As Object = False
Dim isVisible As Object = True
' Here is the way to handle parameters you don't care about in .NET
Dim missing As Object = System.Reflection.Missing.Value
' Make word visible, so you can see what's happening
WordApp.Visible = True
' Open the document that was chosen by the dialog
Dim aDoc As Word.Document = WordApp.Documents.Open(fileName, missing, [readOnly], missing, missing, missing, missing, missing, missing, missing, missing, isVisible) ' Activate the document so it shows up in front aDoc.Activate();
' Add the copyright text and a line break
WordApp.Selection.TypeText("Copyright C# Corner")WordApp.Selection.TypeParagraph()
End If
End
Sub 'button1_Click

This will automatically place an assembly in your application directory that wraps COM access to Word.  Now we are ready to create a word object in our code.  To instantiate an instance of a Word application, you just declare the line below in your class:

Private WordApp As New Word.ApplicationClass()

Now you can call the interesting methods and properties that Microsoft Word provides to you to manipulate documents in Word.  Personally, I never want to figure the Microsoft Word code out myself, because the Word hierarchy and properties, although rich in features, has a bit of a learning curve.  So in order to jump straight over the learning curve, I simple turn the Macro Recorder on in Word and let Word write the code for me.  (Of course this is VBA code, but...close enough).  To start the macro recorder in Word, go to Tools->Macro->Record New Macro inside Microsoft Word.  Now anything you type, open, delete, or format, will get recorded in VBA, so you have a clue how to write your Word Interoperability code.

The application in this particular article is divided into two methods based on the button that is pressed in the form.  The first button opens an existing Word Document and adds a copyright line to the document.  The second button creates a new document, and brings up a dialog to allow you to enter a title to the document.

Below is the code for the first button event handler:

Private Sub button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) '
' Use the custom dialog to get the title of the document from the user
Dim theQueryDialog As New TitleQuery
If theQueryDialog.ShowDialog() = DialogResult.OK Then
' vba code generated from recorded macro to "remind me" how to do it.// ****************************************************************
' Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
' Selection.Font.Bold = wdToggle
' Selection.TypeText Text:="Creating a Title"
' Documents.Add Template:="C:\My Documents\CSharp Book Project\Normal.dot", _
' NewTemplate:=False, DocumentType:=0
' ****************************************************************
' Set up all the parameters as generic objects so we can pass them in //
'Documents.Add
Dim missing As Object = System.Reflection.Missing.Value
Dim fileName As Object = "normal.dot"
' template file name
Dim newTemplate As Object = False
Dim docType As Object = 0
Dim isVisible As Object = True
' Create a new Document, by calling the Add function in the Documents collection
Dim aDoc As Word.Document = WordApp.Documents.Add(fileName, newTemplate, docType, isVisible)
' need to see the created document, so make it visible
WordApp.Visible = True
aDoc.Activate()
' Global Constant enumerations are members of Word and can beassignedproperties
' Set alignment to the center of the document WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;
' Toggle the title to a Bold Font
WordApp.Selection.Font.Bold = CInt(Word.WdConstants.wdToggle)
End If ' Type the Text of the Title that was inputted by the user in the CustomDialog WordApp.Selection.TypeText(theQueryDialog.Title); }}
End Sub 'button2_Click

The code above is a little less intuitive, so I used the Macro Recorder in VBA to spit out the VBA code for creating a document.  Creating a document is done through the Documents Collection.  The Add method of the Documents Collection creates a new document and brings it up in Word.  The Add method allows you to specify the template to use and the document type.  Note that the Add method also takes optional parameters, so as a result, you need to pass it a series of references to objects that box the types you would normally pass. 

The title being placed in the document is formatted using some of the existing Word global enumeration constants.  These constants tend to be constants nested in constants for organizational purposes.  Although VBA gives you a clue to the relative name of the constants, you need to hunt for them a little bit using intelligence to find the parent enumeration.  The code above uses the global enumerations to first center the title and then make it bold.  The final line is similar to the previous listing in that it types the title into the Document.

Conclusion

I hope this article gives you a head start in controlling word from .NET and VB.NET.  It's a little more cumbersome than VBA but it's much less cumbersome than Visual C++ and MFC.  Remember to take advantage of the Microsoft Word Macro Recorder to help you along (this helpful hint also applies to coding in excel and other Microsoft products).  Hopefully with a little coding and the power of .NET Rapid Application Development, you can add some very powerful reporting features to your applications that incorporate Microsoft Word.

Affiliation Links:  Excel VBA Made Easy  Learn MS Office the Easy Way  Passing Microsoft Certification  Basic Programming 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by serin thomas on Aug 23, 2010
bvhjvhjvh b n, b
nnn
 [Top] Rate this article
 
 About the author
 
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE and MEng EE from Cornell University and has consulted for Chase Manhattan Bank, JP Morgan, Merrill Lynch, and Charles Schwab. Currently he is a senior developer at Finisar Corp. He has been involved in several .NET book projects, and is currently working on a book for using .NET with embedded systems.

He can be reached at mike@c-sharpcorner.com

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the top 5 tips for understanding .NET
Ricky Leeks presents the top 5 tips for understanding .NET Interoperability. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
 Comments
Thanks by John On June 8, 2007
Your solution is great. What a nice use of Reflection! You just saved me a huge headache. Regards, jmixon
Reply | Email | Modify 
I love it but... by Alice On June 12, 2007
This works fantastic the first time through. If I click the button to open a second document I get the following error: RPC Server is unavailable. Exception from HRESULT: 0x800706BA Did I miss a piece of configuration or am I not closing/ending some object/process that needs closing? I'd appreciate any insight you have on this. Thanks!
Reply | Email | Modify 
how can I write text in a frame to a worddocument with vb.net by WILLY On June 20, 2007
Is it possible with frames or have I to use the ASCII character codes chart 2 with the graphic characters : chr(176)...chr(223) ? I will be very greatfull if you can help me. Thanks
Reply | Email | Modify 
Regarding COM Reference For MS Word by Divyesh On July 31, 2007
Can i use Windows XP 's wod Reference for Windows 2000's word Reference??
Reply | Email | Modify 
passing parameters to word document... by Scott On January 24, 2008
Good Job Mike... This was very benificial to me and worked just fine.... The thing that I need now is a way to pass parms or values to the word document (like mail merge)... Do you have a code snippet that will do that? Thanks again Mike, -scott
Reply | Email | Modify 
passing parameters to word document... by Scott On January 24, 2008
Good Job Mike... This was very benificial to me and worked just fine.... The thing that I need now is a way to pass parms or values to the word document (like mail merge)... Do you have a code snippet that will do that? Thanks again Mike, -scott
Reply | Email | Modify 
Accessing Word stored as image by Doug On February 25, 2008
Mike, Is it possible to read the contents of Word docs stored as images in sql2005 without opening word on the client side. I need to be able to read the text, highlight keywords with html tags and then spit the result out to an html page. I tried regular expression by reading the doc into a byte array and then converting to a string, but the structure of word made the result very messay. Appreciate any help you can give me.
Reply | Email | Modify 
Can U improve it? by nguyen thanh On May 9, 2009

I want to open ms word 2003 in vb.net form. I found an example like that. But it's C# Application. Can U help me?

Reply | Email | Modify 
Open a word Doc by mahdi On July 2, 2009
How can I open a word doc from vb.net  without using open dialog box (by code only) 
Reply | Email | Modify 
Great! by Marcele On August 27, 2009
Thanks for help!
Reply | Email | Modify 
Read from word by Renoald On September 13, 2009
it is possible read the character or content from word by using vb? since the format word are not same with txt files.
Reply | Email | Modify 
Really a good side by arindam On November 21, 2009

I am really happy after visiting your sight and be a member of your side.

Because my two great programming problems are solved for the help of your

Sight.

Question: Suppose I develop a software and I am not interested to submit the code just I can submit the set-up of it’s demo .Is it possible?

 

Reply | Email | Modify 
word from .net by chauhan On December 11, 2009
its a very good, excellent solution......
I thanks a lot........
Reply | Email | Modify 
how can i add a picturev in a document by wordfromdotnet by sepide On January 26, 2010
hi darling
how can i add a picturev in a document by wordfromdotnet?
how can i write a text or add a pic to a certain position
Reply | Email | Modify 
hi by sepide On January 26, 2010
hi darling
how can i add a picturev in a document by wordfromdotnet?
how can i write a text or add a pic to a certain position
Reply | Email | Modify 
Accessing the contents of Word docs via vb.net by Marc On February 17, 2010
Thanks for the quick response Mike.
However this is not what I'm really looking for.
The objective is to store small word documents (a few pages with text and graphs/pictures per doc only) on the c-drive. The vb.net application should allow the user to see the content of a word document (in read only) without opening Word.

Solution: in my case I tested several possibilities and the best one is to save the Word files as *.RTF and read them into a Rich Textbox. In order to use a "Try & Catch" I used the Word.Application. Not completely correct but it works now.

Dim StreamToDisplay As StreamReader
        Dim word As New Word.Application
        Dim doc As Word.Document
        StreamToDisplay = New StreamReader("C:\Info\Docs\Manual.rtf")
        Try
            doc = word.Documents.Open("C:\Info\Docs\Manual.rtf")
        Catch ex As Exception
            MessageBox.Show("Error accessing RTF document")
        End Try
        rtbARR_REG.Rtf = StreamToDisplay.ReadToEnd
        StreamToDisplay.Close()
        rtbARR_REG.Select(0, 0)

Best regards and thx again
Reply | Email | Modify 
hi by mohamoud On June 17, 2010
Mohamoud
Dear sir can you help me were i can download vb.net 2010
furaat2007@hotmail.com
Reply | Email | Modify 
Nice articles, thanks for sharing. by harry On July 20, 2010
nice article,Microsoft does not recommend using Office application in server-side scenarios. There are great 3rd party .net word document components in the market that do the same job (or even better).
From a comparison testing I performed about a year ago Spire.Doc for .NET is the best.
more details,
http://www.e-iceblue.com/Introduce/word-for-net-introduce.html

maybe help to every.

Reply | Email | Modify 
Re: Nice articles, thanks for sharing. by Mike On July 20, 2010
This isn't really a server side scenario :-).  The article covers automation on the client side, but thanks for sharing the info.
Reply | Email | Modify 
Re: Re: Nice articles, thanks for sharing. by harry On July 30, 2010
Thank you for the reminder, I hope you write more good articles.
Reply | Email | Modify 
help by Ajay On July 21, 2010
how to open ms word by default in iframe in asp.net c#
Reply | Email | Modify 
Help me to open a word file from server on web application by samane On August 2, 2010
hi

i use this code in asp.net web apllication  for open  a doc file from server on client

but it cant open  and don't  erase any error


please help me


ApplicationClass oApplicationClass  = new ApplicationClass();

DocumentClass D = new DocumentClass();

object nullobj = System.Reflection.Missing.Value;

oApplicationClass .Documents.Open(ref fileName,

ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,

ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj,

ref nullobj, ref nullobj, ref nullobj, ref nullobj, ref nullobj);



























Reply | Email | Modify 
DOUBT by aishu On September 1, 2010
HOW SHOUL I CREATE TABLES IN VB.NET FOR MS WORD .ITS IN WINDOW FORM ITSELF NOT IN WORD DOCUMENT.I DON WANT TO OPEN WORD FROM VB. SEND ME SOLUTION SOON
THANKS & REGARDS,
AISHU
Reply | Email | Modify 
how to open this word document inside windows form. by vaibhav On September 13, 2010
Hi ,
this word document is opening separately.
I want to open this eord document inside same windows form. how should i do this?
please help me/.....
Reply | Email | Modify 
Thanx .. All Best by Popi On September 14, 2010
thank you for your's articles, It's very nice ... thanx again

all best :)
Reply | Email | Modify 
how to create different chart in excel using vb.net by satheesh On October 14, 2010
this article information was very useful thank u ....
i want to draw different charts in excel using vb.net ..if we click button it have create excel and have to show file with charts... c'd u help me...?
Reply | Email | Modify 
using wordpad by Humita On January 24, 2011
Hi Very interesting, can I do it, using Wordpad instead of Word? Which library can I use Regards,
Reply | Email | Modify 
Code doesn't work by Sue On April 26, 2011
I followed the instructions above exactly, but the code doesn't work.I receive the error Word.ApplicationClass' is not defined. Please help!
Reply | Email | Modify 
Re: Code doesn't work by Mike On April 27, 2011
Hi Sue, the implementation to talk to word has changed in 2010. If I get a chance, I'll rewrite the article for 2010. but i've been pretty swamped lately. the good news, it is much easier in VS2010. You don't need so many paramaters anymore, and you don't need to worry about coercing types, the types are automatically mapped through the magic of the DLR!
Reply | Email | Modify 
Re: Re: Code doesn't work by Sue On April 28, 2011
Hi Mike: Thank you for your reply. I'm sorry I was so short on details. I am using Visual Web Developer 2008 (Express Edition) and I have a feeling it is not working correctly. I added a reference to the COM Microsoft Word 12.0 Object Library (9.0 was not available). I added the 'Import Namespace="Microsoft.Interop.Word"' at the top of the web-page. I have the vb.net code and the asp.net controls all in one web-page with the vb.net inside the <script> tags. Unfortunately, it tells me that the Word.ApplicationClass is not defined. I've tried several different code samples from the web but they did not work either. I'm just very frustrated at this point. I appreciate your help.
Reply | Email | Modify 
time waster by praveen On August 6, 2011
bustard
Reply | Email | Modify 

 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.