Professional Documents
Culture Documents
Memo
To: Wekkel
From: Wekkel
CC:
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.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 ->
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
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.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.
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
Try
wordDoc = wordApp.Documents.Add()
wordApp.Visible = True
Page 3
Catch ex As Exception
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.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
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.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.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.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
Try
wordDoc = wordApp.Documents.Add()
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
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.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.
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
Try
wordDoc = wordApp.Documents.Add(wordfile)
wordApp.Visible = True
wordDoc = wordApp.ActiveDocument
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
With myStoryRange.Find
.Text = Findtext
.Replacement.Text = Replacetext
.Wrap = WdFindWrap.wdFindContinue
.Execute(Replace:=WdReplace.wdReplaceAll)
End With
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
Catch ex As Exception
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.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.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.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
'do something
WordApp.ActiveWindow.Selection.Font.Bold = False
WordApp.ActiveWindow.Selection.Font.Italic = True
'do something
WordApp.ActiveWindow.Selection.Font.Italic = False
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
Page 10
If WordApp Is Nothing Then
WordApp = CreateObject("Word.application")
End If
On Error GoTo 0
WordDoc = WordApp.documents.Add
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.1. The following subprocedure renders a message box showing the current version of
Word on the PC.
objWord = CreateObject("Word.Application")
objWord.Quit()
objWord = Nothing
End Sub
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.
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:
Page 13
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles Button1.Click
MessageBox.Show("Mijn naam is " & Test1.TxtNaam.Text & " en ik ben een " &
Test1.cbRechtsvorm.Text)
MessageBox.Show("My name is " & Test1.TxtNaam.Text & " and I am a " &
Test1.cbRechtsvorm.Text)
Else
End If
End Sub
End Class
Page 14