Word Automation using VB.NET


In this article i have explained how to automate word applications with the help of VB.NET, Many peoples are not aware of COM interop applications, this is a basic article that gives idea about the word automations.

Word Automation using VB.NET

Index
Introduction
Working with Word interop
Start with code
Read content of Word file
Create a new word file and write in it
Print a document without opening it
Convert word document to HTML page


introduction
Recently i have worked with Interop objects, may be you have heard about this word. Interop are unmanaged object. basically COM Interop is a
technique to included COM objects in .NET to interact objects. Component Object Model (COM) interop expose object and it's functionality to other components
and use them to host various applications


Working with Word interop
In this article we are going to deal with Word interop objects. we can automate word files using this interoperability.
to automate word programmatically we need to add it's word interop assemblies.
we need Office 2003 or 2007 and VB.NET (here i used office 2003)

now open Visual studio and create new project in VB.NET. After that go to solution explorer Rightclick and add reference
new window will open go to COM tab and select "Microsoft Word 11.0 Object Library" if you have 2007 then you should select "Microsoft Word 12.0 Object Library"
here is snap
Word_Ref




Start with code
At the top of page we need to import reference


Imports word = Microsoft.Office.Interop.Word


yes, we import namespace now start with the actual operation.


Read content of Word file
here is our first task to read content of word file.
we need to create a object of Document and application. here is code


'Open new instance
dim objApp as New Word.Application 'create new object of word application
dim objDoc as New Word.Document 'create new object of word document

objDoc = objApp.Documents.Open(//word file path to open file)
objDoc.Activate()
MessageBox.Show(objDoc.Content.Text) 'Shows the content from word file

'Dispose the word objects
objDoc.Close()
objApp.Quit()
objDoc = Nothing
objApp = Nothing







Create a new word file and write in it
we can create a new word file using word automation and write text in it


'Open new instance
objApp = New Word.Application
objDoc = New Word.Document

objDoc = objApp.Documents.Add() 'add new word file to documents collection
objDoc.Activate() ' activate newly created file
objApp.Selection.TypeText("This the First text") 'insert string in word file
objDoc.SaveAs(//Path of file to save) 'save word file


'Dispose the word objects
objDoc.Close()
objApp.Quit()
objDoc = Nothing
objApp = Nothing







Print a document without opening it


Dim objApp As Word.Application
Dim objDoc As Word.Document
objApp = New Word.Application()
objDoc = objApp.Documents.Open("//Path of a file to Open")
objDoc.PrintOut( _
Background:=True, _
Append:=False, _
Range:=Word.WdPrintOutRange.wdPrintCurrentPage, _
Item:=Word.WdPrintOutItem.wdPrintDocumentContent, _
Copies:="1", _
Pages:="1", _
PageType:=Word.WdPrintOutPages.wdPrintAllPages, _
PrintToFile:=False, _
Collate:=True, _
ManualDuplexPrint:=False)

objDoc.Close();
objApp.Quit();

objDoc = Nothing
objApp = Nothing







Convert word document to HTML page
we can convert word file to web page using word automation


Dim objApp As Word.Application
Dim objDoc As Word.Document
objApp = New Word.Application()
objDoc = objApp.Documents.Open("//Path of a file to Open")

oDoc.SaveAs(FileName:=.FileName.ToString.Replace(".doc", ".htm"), FileFormat:=Word.WdSaveFormat.wdFormatHTML)
oDoc.Saved = True
oDoc.Close(SaveChanges:=False)
oDoc = Nothing





Real world fact
Word is heavy interop object and it is unmanaged resource so GC unable to understand and collect it after use, we have to make force code to
collect the object from meory.
for this perticular code i have used Close() and Quit() methods to dispose word objects.
Word automation may slow down the system processes.


Thanks
Suggestion are most welcome

Thanks
koolprasad2003


Comments

Guest Author: Gary Heath25 Feb 2013

The document I have created is more than one page, how do I position it at the top when the Word document opens for editing ?

Guest Author: thomas mercer27 Mar 2014

I need to add more than one Hyperlink in a document. When I do, it appears at the top and there is no spacing between them. Is it possible to space them apart or put one on the next line, within a sentence.

Author: Prasad kulkarni28 Mar 2014 Member Level: Gold   Points : 4

Hello Gary Heath
What you want to keep your position it at the top of the page ? do you want to keep your cursor at top of the page when document open.
if so, then follow the code below



Dim objApp As Word.Application
Dim objDoc As Word.Document
objApp = New Word.Application()
objDoc = objApp.Documents.Open("//Path of a file to Open")
objApp.Selection.HomeKey(WdUnits.wdStory, Nothing)
objApp.Visible = true

hope it helps

if you have doubt, feel free to ask

Author: Prasad kulkarni28 Mar 2014 Member Level: Gold   Points : 8

Hello thomas
You have added more than one hyperlinks in your document right ? now you want to put one on the next line using program, but why don't you put them initially on separate line.
I mean if you place them manually in document then you can place them in a specific position you want, why you need program for it.
Basically you can move hyperlink from one place to another,
I got little code from MSDN site, that work perfectly to add hyperlink in word document, so can see below


Imports Word = Microsoft.Office.Interop.Word

Public Class Form1

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim wdParagraph As Word.Paragraph
Dim wdNewParagraph As Word.Paragraph

Try
wdDoc = wdApp.Documents.Add()
wdApp.Visible = True

wdParagraph = wdDoc.Sections(1).Range.Paragraphs.Add()
wdParagraph.Range.Hyperlinks.Add(Anchor:=wdApp.Application.Selection.Range, Address:="http://localhost", ScreenTip:="This is a Tesst", TextToDisplay:="Test")
wdNewParagraph = wdParagraph.Range.Paragraphs.Add()
wdNewParagraph.Range.Hyperlinks.Add(Anchor:=wdNewParagraph.Range, Address:="http://localhost", TextToDisplay:="Another Text")
Catch ex As Exception
MsgBox(ex.Message, , "Exception")
End Try
End Sub
End Class

Here is another piece code, that can be also helpful

sPara2 = objDoc.Paragraphs.Add()
sPara2.Range.Text = "This is my hyperlink"
sPara2.Range.Hyperlinks.Add("This is my hyperlink")
sPara2.Format.SpaceAfter = 24 '24 pt spacing after paragraph.
sPara2.Range.InsertParagraphAfter()
sPara2.Range.Hyperlinks.Add("This is my hyperlink2")

hope it helps

Author: Umesh Bhosale01 Apr 2014 Member Level: Silver   Points : 0

Good Article



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: