Introduction
Many developers do not know about Word automation and its advantages. So here is a simple demo program that gives you a brief idea of Word automation using VB.NET. and Word 2003.
Background
Actually my team leader encouraged me to write something on Word automation that would be useful to my juniors. So I searched on MSDN and got some information to automate Word using VB.NET.
Getting Started
To automate Word, you need Word to be installed on your machine. You can use Word 2007/2003. Here we have used Word 2003. Create a new window based application and add a reference to "Microsoft Word 11.0 Object Library". See the following screenshot to add a reference from the COM tab:
After successfully referencing the assembly, start the code.
Import the Namespace
Imports Microsoft.Office.Interop.Word
This will helps us to use its predefined methods and properties.
Create the Objects
Now create Application and Document objects with it's new instance.
Dim objApp As Word.Application
Dim objDoc As Word.Document
objApp = New Word.Application()
objDoc = objApp.Documents.Open("//Path of a file to Open")
Dispose the Objects
Once Word objects are created, after Word has finished, they should be disposes by using the following methods. GC will collect those objects until we make them NULL.
objDoc.Close()
objApp.Quit()
objDoc = Nothing
objDoc = Nothing
Read the Contents of Already Saved Word File
The following code will read the contents of the already saved Word file:
objApp = New Word.Application
objDoc = New Word.Document
objDoc = objApp.Documents.Open(//File Path)
objDoc.Activate()
MessageBox.Show(objDoc.Content.Text) //Shows the content from word file
objDoc.Close()
objApp.Quit()
objDoc = Nothing
objApp = Nothing
Create a New Word File
The following code will create a new Word file and save it:
objApp = New Word.Application
objDoc = New Word.Document
objDoc = objApp.Documents.Add()
objDoc.Activate()
objDoc.SaveAs(//Path of file to save)
objDoc.Close()
objApp.Quit()
objDoc = Nothing
objApp = Nothing
Create a New Word File and Write into it
The following code will create a new Word file and write some text in it and save it:
objApp = New Word.Application
objDoc = New Word.Document
objDoc = objApp.Documents.Add()
objDoc.Activate()
objApp.Selection.TypeText("This the First text")
objDoc.SaveAs(//Path of file to save)
objDoc.Close()
objApp.Quit()
objDoc = Nothing
objApp = Nothing
Points of Interest
As WINWORD is the heavy object, we have to use the Close() and Quit() methods to kill WINWORD instance from task manager. Otherwise it will be pending in a taskmanager. The number of WINWORD instances will go on increasing if we create a NEW object of Word.Application.
Summary
The attached code will give you a brief idea of Word automation techniques. Using the above methods, one can easily automate Word.
History
- 1st February, 2010: Initial post