You are on page 1of 14

Wekkelsoft

Memo
To: Wekkel
From: Wekkel
CC:

Date: 24 January 2010 – Version 1.0


Re: Basics for .NET Word Applications in Visual Basic 2008/2010

1. Introduction and scope

1.1. Introduction

1.1.1. This memo describes the basis setup and code to implement and write .NET
framework 2.0 code for use with Office Word 2003.

1.2. Scope

1.2.1. This memo is aimed at users of Visual Studio (Visual Basic language) who already
know how to navigate around Visual Studio and build a simple Windows Form
Application with a button and attached code.

1.2.2. With the information in this memo, you should be able to perform the basic functions in
Word from your Visual Basic Windows Form Application.

2. Basic setup

2.1. Setup Project in Visual Studio

2.1.1. When setting up a project, add a reference to the Office 11 (2003) Library and the
Office Interop elements. The reference can me made through : Project -> Add
Reference ->

a. Under .NET tab -> Microsoft.Office.Interop.Word 11.0.0.0 (you may want to


click ‘Component Name’ to alphabetically sort the list first)

b. under COM tab -> Microsoft Office 11.0 Object Library

1
Image 2.1.1: adding a reference to your Project

2.1.2. In your form, add a reference to the Interop language by means of the following code
(place it above the text where the form starts with "Public Class Form", see sample
below).

Imports Microsoft.Office.Interop.Word

Public Class Form1

2.2. Setup Office 2003 (PIA Tools)

2.2.1. Please make sure that you have installed Office 2003 with all .NET programmability
and PIA tools installed. If necessary, go to Start -> Settings -> Control Panel -> Add or
Remove Programs and select the Office 2003 package. Choose ‘Add/change’ and
select the required packages for installation.

3. Basic functions with Word

3.1. Important notes

3.1.1. Since we are going to control the Word application ourselves, we should be aware that
the application may run without showing itself. In that case, Winword.exe (the Word
application) would be active, but not visible on the screen. This element is controlled by
the command (to be explained later)

wordApp.Visible = True

 Page 2
3.1.2. Therefore, it is advisable to have the task manager running (Start -> Run -> "taskmgr")
when running your applications from Visual Studio to check whether Word is already
running. If so, first close al running instances of Windword.exe via task manager (with
the button 'End Process' to make sure that they do not interfere with your application.

Image 3.1.2: Task manager showing a running instance of Word

3.2. Creating new Word document

3.2.1. Upon pressing the button, the following code creates an instance of the Word
application, creates a new Word document and finally shows the new document on the
screen.

Imports Microsoft.Office.Interop.Word

Public Class Form1

Dim wordApp As New Microsoft.Office.Interop.Word.Application

Dim wordDoc As Microsoft.Office.Interop.Word.Document

Dim wordfile As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

Try

wordDoc = wordApp.Documents.Add()

wordApp.Visible = True

 Page 3
Catch ex As Exception

MsgBox("Error creating Word document.")

End Try

End Sub

End Class

3.2.2. The command Add() is the key element here. Please note that new documents are
added within the same Word instance if the button in the windows form application is
clicked multiple times.

3.2.3. To make sure that the Word application will be visible, the parameter 'Visible' is set to
'True'.

3.2.4. The code contains some basic error handling, if only to know that an error occurred.

3.3. Opening existing Word document

3.3.1. The sample code assumes that a test.doc Word document is present at the location
shown. Upon pressing the button, the following code creates an instance of the Word
application, opens an existing Word document from the shown location and finally
shows the new document on the screen.

Imports Microsoft.Office.Interop.Word

Public Class Form1

Dim wordApp As New Microsoft.Office.Interop.Word.Application

Dim wordDoc As Microsoft.Office.Interop.Word.Document

Dim wordfile As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

wordfile = "c:\test\test.doc" ' path and file name goes here

Try

wordDoc = wordApp.Documents.Open(wordfile)

wordApp.Visible = True

Catch ex As Exception

 Page 4
MsgBox("Error accessing Word document")

End Try

End Sub

End Class

3.3.2. The command Open() is the key element here.

3.3.3. Please note that the Word document is opened in a new instance of the Word
application. If an instance of Word is already running, the Windows Form Application
will open a new instance of Word instead of opening the Word document in the already
running Word application. We will get back to that in a moment.

3.4. Opening existing Word template

3.4.1. Basically, the same routine applies as opening a new Word document. Use the
command Add() instead of Open(). Doing so, will create a new Word document based
on the chosen template, without opening the template as a document.

3.5. Saving Word document

3.5.1. The sample code assumes that a test.doc Word document is present at the location
shown. Upon pressing the button, the following code creates an instance of the Word
application, creates a new Word document, adds text to it with the 'Range' element and
finally saves the new document to the specified location.

Imports Microsoft.Office.Interop.Word

Public Class Form1

Dim wordApp As New Microsoft.Office.Interop.Word.Application

Dim wordDoc As Microsoft.Office.Interop.Word.Document

Dim wordfile As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

Try

wordDoc = wordApp.Documents.Add()

Dim insertText As String = "Text inserted at the beginning of the document."

 Page 5
Dim range As Microsoft.Office.Interop.Word.Range = wordDoc.Range(Start:=0,
End:=0)

range.Text = insertText

wordDoc.SaveAs("c:\test\test2.doc")

Catch ex As Exception

MsgBox("Error accessing Word document.")

Finally

wordDoc.Close(True)

wordApp.Quit()

End Try

End Sub

End Class

3.5.2. The command Save() is the key element here. The 'Range' element will be discussed
later.

3.5.3. Please note that the instance of the Word application is not set as visible (Visible=True);
the user won't see on his screen that Word has been active.

3.6. Using the location of your application

3.6.1. For some tasks, it is necessary to refer to a Word document shipped with your program.
Since the installation path of the application may differ, a relative path is required. The
following variable holds the application path and, subsequently, defines 'docName' as
the file to use.

Dim ApplicationFolder As String = System.Windows.Forms.Application.StartupPath

Dim docName As String = ApplicationFolder &


"\documenten\volmachten\Volmacht.Aanvaarding.Verpanding.Aandelen.EN.dot
"

4. More advanced Word functions

4.1. Find and Replace text in a Word document

 Page 6
4.1.1. The sample code assumes that a replacetekst.dot Word template is present at the
location shown. Upon pressing the button, the following code creates an instance of the
Word application, creates a new Word document from the template and replaces
certain text with other text.

Imports Microsoft.Office.Interop.Word

Public Class Form1

Dim wordApp As New Microsoft.Office.Interop.Word.Application

Dim wordDoc As Microsoft.Office.Interop.Word.Document

Dim wordfile As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles Button1.Click

wordfile = "c:\test\replacetekst.dot" ' path and file name goes here

Try

wordDoc = wordApp.Documents.Add(wordfile)

wordApp.Visible = True

wordDoc = wordApp.ActiveDocument

Dim Findtext As String = "Dummy1"

Dim Replacetext As String = "Wekkel"

Dim myStoryRange = wordDoc.Range()

'First search the main document using the Selection

With myStoryRange.Find

.Text = Findtext

.Replacement.Text = Replacetext

.Forward = True

 Page 7
.Wrap = WdFindWrap.wdFindContinue

.Format = False

.MatchCase = False

.MatchWholeWord = False

.MatchWildcards = False

.MatchSoundsLike = False

.MatchAllWordForms = False

.Execute(Replace:=WdReplace.wdReplaceAll)

End With

'Now search all other stories using Ranges

For Each myStoryRange In wordDoc.StoryRanges

If myStoryRange.StoryType <> WdStoryType.wdMainTextStory Then

With myStoryRange.Find

.Text = Findtext

.Replacement.Text = Replacetext

.Wrap = WdFindWrap.wdFindContinue

.Execute(Replace:=WdReplace.wdReplaceAll)

End With

Do While Not (myStoryRange.NextStoryRange Is Nothing)

myStoryRange = myStoryRange.NextStoryRange

With myStoryRange.Find

.Text = Findtext

.Replacement.Text = Replacetext

.Wrap = WdFindWrap.wdFindContinue

.Execute(Replace:=WdReplace.wdReplaceAll)

 Page 8
End With

Loop

End If

Next myStoryRange

'show message box

MsgBox("Replaced all instances")

Catch ex As Exception

MsgBox("Error accessing Word document")

End Try

End Sub

End Class

4.1.2. The text to be found is contained in the variable 'Findtext' and the text to be inserted is
contained in the variable 'Replacetext'.

4.2. Place text in a Word document via an existing Bookmark

4.2.1. The following code can be used to insert text generated within your application into the
active Word document at a Bookmark placed in the Word document. Please note that
the Bookmark remains in the Word document after inserting the text. The variable 'text'
must contain a String and the variable 'bookmark' must contain a bookmark that exists
in the Word document.

wrdApp.ActiveDocument.Bookmarks(bookmark).Range.Text = text

4.3. Insert text in a Word document at cursor

4.3.1. The following code simply inserts text in the active Word document at the cursor. The
variable 'text' must contain a String.

WordApp.ActiveWindow.Selection.TypeText(text)

4.4. Apply different formatting styles in Word document

4.4.1. The following code sets the Word document ready for accepting text in Bold or Italics,
just as it would when pressing the appropriate button in Word itself. See example code
below for Bold and Italics.

 Page 9
WordApp.ActiveWindow.Selection.Font.Bold = True

WordApp.ActiveWindow.Selection.TypeText("This is a text in Bold" & vbCrLf)

'do something

WordApp.ActiveWindow.Selection.Font.Bold = False

WordApp.ActiveWindow.Selection.Font.Italic = True

WordApp.ActiveWindow.Selection.TypeText("This is a text in Italics")

'do something

WordApp.ActiveWindow.Selection.Font.Italic = False

4.5. Check if Word application is running

4.5.1. It is much more intelligent to check whether the Word application is already and, if so,
using it, than to start a new Word application without checking first. The following code
does just that.

Imports 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 WordApp As Object, WordDoc As Object

On Error Resume Next

'~~> Check if Word is already Open

WordApp = GetObject(, "Word.application")

 Page 10
If WordApp Is Nothing Then

'~~> If no instance of Word is found then open one

WordApp = CreateObject("Word.application")

End If

On Error GoTo 0

'~~> Add a new Document

WordDoc = WordApp.documents.Add

'~~> Display Word

WordApp.Visible = True

End Sub

End Class

5. Miscellaneous

5.1. Icons

5.1.1. It is possible to add icons to the Windows Form Application. Axialis Software has a free
Icon editor that works with Visual Studio 2008 (and Visual Studio 2010). Double Click
'My Project' in Visual Studio and go to 'Resources'. Add a resource, being an icon file.
This icon file is placed in the Project's folder and can be edited with Axialis icon editor.
After editing is done, the icon can be added to the Project in Visual Studio under
Application -> Icon in the Project's settings.

 Page 11
Image 5.1.1: Add an icon to your project

5.2. Check which Word version is present

5.2.1. The following subprocedure renders a message box showing the current version of
Word on the PC.

Private Sub CheckWordVersion()

Dim objWord As Object

objWord = CreateObject("Word.Application")

MsgBox("Word version is: " & objWord.Version)

objWord.Quit()

objWord = Nothing

End Sub

5.3. Add custom user control to toolbox

5.3.1. To add a custom user control to the tool box, right click on your project in the solution
explorer and 'Add' -> 'control'. This control is automatically added to your toolbox after
you build your project. The custom control is now ready for reuse in your project.

 Page 12
Image 5.3.1: Add a user control to your project

5.3.2. The new user control should be available in the Toolbox after building the project. You
may have to swith the toolbox view to 'Show all' to see the new custom user control.

Image 5.3.2: Show all items in Toolbox

5.3.3. To use the custom user control in a form, drag the newly created user control from the
toolbox onto the windows form. To access the properties contained in the user control
form, a reference to the user control is necessary. It is necessary to start with 'Test1'
before a reference to the controls themselves can be made. In the following example
code, the following basics apply:

a. Test.vb is my custom user control; and

b. on my windows form, the custom user control is (automatically) named Test1.

Public Class Form1

 Page 13
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click

'custom code, not included in Test.vb

If Test1.RdNL.Checked = True Then

MessageBox.Show("Mijn naam is " & Test1.TxtNaam.Text & " en ik ben een " &
Test1.cbRechtsvorm.Text)

ElseIf Test1.RdNL.Checked = False Then

MessageBox.Show("My name is " & Test1.TxtNaam.Text & " and I am a " &
Test1.cbRechtsvorm.Text)

Else

End If

End Sub

End Class

 Page 14

You might also like