programming word - 1st edition (2014)

Upload: wekkel

Post on 07-Jul-2018

220 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/19/2019 Programming Word - 1st Edition (2014)

    1/153

    2/24/2015 programming_microsoft_word_-_01_introduction - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_01_introduction 1/3

    Programming Microsoft Word - 01 -Introduction

    Introduction

    I have been planning for several years to automate some of the repetitive Word tasks I encounter on adaily basis. For companies, software development is not something purchased like a box of printer ink

    and pencils. It involves a lot of planning, testing, interviews and … money. There seems to be no chancein getting your own repetitive tasks automated very quickly. Well, that's were opportunity is arising.Writing software becomes easier and easier. Open source tools but also tools made available bycompanies like Microsoft increase our ability to be our own developer and solving our own challenges athome and at work.

    This contribution to Devtome is intended to be the first of many, describing the steps to develop asoftware application with free tools (assuming you have MS Word available). A software applicationthat you can fit and mold to your exact requirements, saving you a lot of time and trouble in your futureambitions and work. I am not and will never be a professional coder. It's all about reading, trying out and

    education oneself in the long run, and making software that works (whether we fully understand it or not). Since I have not encountered a single source of information explaining all basic aspects of building

    our Word automation project, I have made it my aim to do exactly that. A guide for enthusiasts willingto put in the effort to learn automating their documents.

    This first contribution kicks off with a small introduction, followed by setting up the necessary (free)software, and finally building and running a simple program that automates Word. This little programwill not be the end - there are a lot of issues with it that need to be solved; something we will tackle infuture contributions - but we take it step by step. You will do some coding of yourself. That means youwill actually be writing a program and executing it. Don't worry, the code will be provided to you so it

    can't go wrong. I will use the following box to describe code.

    [[ code goes in here ]]

    Most of the coding will be done by the programming software. Your task mainly consist of building theuser interface with drag and drop and inserting some minimal code at the right spot to make it work. Youwill learn quickly how it works and become familiar with it.

    Automating Microsoft WordEverybody knows Microsoft Word. This program is still number 1 software used in most businesses andwidely known to people all over the world. The amount of hours spent behind a keyboard, typing inletters that form words, that form sentences, that form … etc, is endless. What is less known is Word's

  • 8/19/2019 Programming Word - 1st Edition (2014)

    2/153

    2/24/2015 programming_microsoft_word_-_01_introduction - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_01_introduction 2/3

    design. As from the start, Microsoft made Word very much programmable. In lay men's terms: theability to let Word do things automatically by means of a program. Some of these automation tasks arealready baked in Word itself. An example is the Table of Contents, that can be added to a document within-build functionality. A rudimentary form of automation that you can build yourself is the macro.Macro's can be created by the Word user by recording a task, which can be repeated by means of thismacro endlessly by means of a short-cut or a button assigned to this macro, thus saving the user time andeffort. In fact, I think most people already use these automation options of Word, whether by own design

    or by design of their employer.However, Word can be automated a lot further.

    Assuming that you or your employer already has bought Microsoft Word, you already have a very powerful tool at hand to bring you those documents, letters and reports. Word can do a lot more than justtaking keyboard strokes one by one. It is designed to be programmed and steered by external programsin almost every conceivable way. Generally, users do not use even 10% of its capabilities. In conclusion,the complete engine for our automation is already there, bought and paid for.

    Required toolsAs stated above, I assume you already have Microsoft Word available. It does not matter which version

    ou use. With some small adjustments, the approach to Word automation used in this contributionshould work for each recent version of Word. The rest of the software needed is basically one additional

    program only: Microsoft Visual Studio Express (for Desktop). Since Microsoft came out with.NET, ithas also been releasing newer versions of its related programming software: Visual Studio (VS).Whereas the full versions of VS come at a price, Microsoft also makes limited versions of VS freelyavailable: the 'Express' version. With hardware moving from desktop to the web and, nowadays, mobile,there are several different types of Visual Studio Express 2013 to choose from. For this contribution, wewill use Visual Studio Express for Desktop 2013.

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    3/153

    2/24/2015 programming_microsoft_word_-_01_introduction - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_01_introduction 3/3

    Download and install Visual Studio Express for Desktop [http://www.visualstudio.com/en-us/downloads/] .Installing takes some time. If the program asks you what programming language you will primarily beusing, choose Visual Basic. Once installed, you are ready to start with the first program.

    Next: Programming Microsoft Word - 02 - Our first program [http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program]

    Computing | Programming | Software

    programming_microsoft_word_-_01_introduction.txt · Last modified: 2014/08/20 17:05 bywekkelExcept where otherwise noted, content on this wiki is licensed under the following license: CCAttribution-Share Alike 3.0 Unported [http://creativecommons.org/licenses/by-sa/3.0/]

    Advertise with Anonymous Ads

    http://www.devtome.com/doku.php?id=start&do=recenthttp://www.devtome.com/doku.php?id=category:softwarehttp://creativecommons.org/licenses/by-sa/3.0/http://www.devtome.com/doku.php?id=category:programminghttp://www.devtome.com/doku.php?id=category:computinghttp://a-ads.com/?partner=5552http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_programhttp://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    4/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 1/13

    Programming Microsoft Word - 02 - Our first program

    Let's get started and write the first program

    After the Introduction [http://www.devtome.com/doku.php?id=programming_microsoft_word_-_01_introduction] , it's time for us to write our first program automating Word.We will build a simple Windows form that will take text input and write it in a new Word document at the place of the cursor.

    The Word version used is 2007 but it should work with other Word versions as well (older and newer).

    If not already done so, Download and install Visual Studio Express for Desktop [http://www.visualstudio.com/en-us/downloads/] .

    Working with Visual Studio Express

    Start Visual Studio. If the program asks you which language you will primarily be working with, chose 'Visual Basic. Soon, you will be looking at the IDE of this program. This may seem a bit overwhelming the first time, but you will know your way around fairly quickly.

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_01_introductionhttp://www.visualstudio.com/en-us/downloads/http://www.visualstudio.com/en-us/downloads/http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    5/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 2/13

    You will be working with this IDE a lot, so here is a basic introduction. You are looking at the default look of Visual Studio (VS) right after the start. On top, you findthe familiar menu's for opening and closing files, edit, view etc. The rest of the screen is used for window boxes that will help you write your first program.

    On the left, there's the 'toolbox'. The toolbox will show all kinds of tools like buttons, textboxes and other stuff that you will need for your program. It works with dragand drop, placing items on the Windows form of your program. In the middle window, you find the tabs on top to switch between files. Most of the coding will be donein this window, so some screen estate will come in handy to fit this between the toolbox on the left and the solution explorer on the right.

    The middle window on the bottom will by default be an error list, showing possible errors in your code so you can have an immediate look at it while coding.

    Finally, on the right side there is the 'solution explorer' that will show project files like some sort of file browser. We will not be using this in this contribution. On thelower right side, when working on a project you will see a list of properties of a particular selected object. This window allows you to look up and change properties of objects (like the name of a button).

    If you feel uncomfortable about is, I recommend that you follow http://www.youtube.com/watch?v=pp5UuZxayCk to get a first feeling of working with the IDE.

    Start a new project

    Step 1

    First, you need to open a new project. Select File → New Project and choose a Visual Basic - Windows and choose 'Windows Form Application' from the options.Give your project a name (like “MyFirstMSWordProgram”) and click 'OK'.

    http://www.devtome.com/doku.php?id=this_tutorialhttp://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    6/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 3/13

    Step 2

    Once the project is loaded, we need to make a reference to the Office library. This library basically enables you to 'talk' to Word programmatically and make it dothings. This is called 'Interop', a term you will use when writing the code. The program elements to steer Word, must be linked to our project and we will do this with

    Visual Studio by making a reference to the so-called Office Object Library. For Word 2007 it is version 12 (2003 is 11, 2010 is 13 etc).The reference is made as follows : (top menu) Project → Add Reference →

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    7/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 4/13

    Step 3

    In the resulting window, choose under the 'COM' element → Microsoft Office 12.0 [or your version of Word] Object Library. The search field as shown below canhelp you locate this reference easier.

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    8/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 5/13

    Click OK and you are all set.

    Working with some code

    Ok, we still need to do one thing before we can program Word. In the IDE's middle window, you find the empty Windows form (a grey rectangle). By default, VS callsthis rectangle 'Form1'. Double click the Form1. The IDE will go to the code behind the Form.

    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 Form1”, seesample below).

    Imports Microsoft.Office.Interop.Word

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    9/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 6/13

    It is possible that this line of code gives you errors. The automatic help for inserting text will not let you choose Interop and/or the error list in the middle windowelow will start to complain about errors. In that case, make sure that you have installed the so-called Primary Interop Assemblies (PIA) for Word for your Wordersion. In my example, the PIA for Word 2007 version can be found here [http://www.microsoft.com/en-us/download/confirmation.aspx?id=18346] .

    Designing the GUI of our program

    Our program will be steered from the Graphical User Interface (GUI). This is a familiar Windows form on which we will place a textbox and a button. The textbox andutton can be dragged with the mouse from the toolbox on the left onto Form1 (see picture below). Drag them around and resize them as fit. We will not change their

    names in this round.

    http://www.visualstudio.com/en-us/downloads/http://www.microsoft.com/en-us/download/confirmation.aspx?id=18346

  • 8/19/2019 Programming Word - 1st Edition (2014)

    10/153

  • 8/19/2019 Programming Word - 1st Edition (2014)

    11/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 8/13

    Coding time

    Now for some action. Double click the button you just dragged onto Form1. The IDE will show you the code behind that button and places the cursor ready to insertsome code. Alternatively, you can switch to the code behind Form1 by right-clicking 'Form1' in the Solution Explorer (see picture), but then you will have to go to the

    lock that holds the code for the button yourself.

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    12/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 9/13

    You will be inserting the following code on that exact spot:

    Dim wdApp As New Word.ApplicationDim wdDoc As Word.Document

    TrywdDoc = wdApp.Documents.Add()wdApp.Visible = TrueCatch ex As Exception

    MsgBox("Error creating Word document.")End Try

    wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)

    wdApp = Nothing

    When done, it will look like this:

    We will go through this code step by step explaining what it does, but first let's run the program!

    http://www.visualstudio.com/en-us/downloads/http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    13/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 10/13

    Running the program

    The button 'Start' will build our program and subsequently run it as a regular Windows program. VS will not let you run the program if there are still errors in the code.

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    14/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 11/13

    The program is running successfully. In the example above, I inserted some text in the textbox. Write some text in the textbox yourself and press the button.

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    15/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 12/13

    Voila, the end result. The program has opened a new Word document and inserted the text from the textbox in the Word document at the place of the cursor (=start of Word document). Your first manipulation of Word by means of a software program…

    How does this code work?

    Below, we will go through the code in more detail but first the warning that his code is not suitable yet for our purposes. You will notice that - if you had Word alreadyrunning - a second version of Word was started that will conflict with the earlier running version. If you close the newly created document and close the 2nd version of Word running, it will complain about another version of Word running. Close Word but do not overwrite the normal.dot file. We will fix this behaviour in futurecontributions.

    Now the code.

    1. With the 'Dim' command, we make sure that the program knows that there will be a Word object (Word.Application → the Word software) and a Word documentobject (Word.Document → a Word document).

    2. The code 'try, catch and End try' is inserted to perform some basic error handling. If an error would occur when executing the code and no error handling is provided,our program would crash. Now, an error would trigger a message box indicating something went wrong. Proper error handling is very important when writingsoftware.

    3. the command 'wdDoc = wdApp.Documents.Add()' basically starts Word (whether already running or not) and opens the default blank document. With'wdApp.Visible = True', we make sure that Word will be visible on screen.

    4. The command to type text into a Word document at the place of the cursor is 'wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)'. Behind TypeText wecould have added text between ”” ourselves, but instead, we point the program to the contents '.Text' of our textbox (which by default is named 'TextBox1').

    5. the object wdApp is made 'nothing' again as clean up afterwards.

    Next contribution: step by step

    The next contribution deals with the GUI. We will create a little program that hides in the Windows tray and will show a menu when right-clicked with the mouse. Thismenu will hold all our future Word actions, so that we will have Word automation ready at our fingertips when needed.

    http://www.visualstudio.com/en-us/downloads/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    16/153

    2/24/2015 programming_microsoft_word_-_02_-_our_first_program - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program 13/13

    Next contribution (part 3) [http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray]

    Computing | Programming | Software

    programming_microsoft_word_-_02_-_our_first_program.txt · Last modified: 2014/08/20 17:04 by wekkelExcept where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported[http://creativecommons.org/licenses/by-sa/3.0/]

    Advertise with Anonymous Ads

    http://creativecommons.org/licenses/by-sa/3.0/http://www.devtome.com/doku.php?id=category:computinghttp://www.devtome.com/doku.php?id=start&do=recenthttp://www.devtome.com/doku.php?id=category:softwarehttp://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_trayhttp://a-ads.com/?partner=5552http://www.devtome.com/doku.php?id=category:programming

  • 8/19/2019 Programming Word - 1st Edition (2014)

    17/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 1/12

    Programming Microsoft Word - 03 - Running the program from the tray

    Giving our program a place to start

    In the previous post [http://www.devtome.com/doku.php?id=progr amming_microsoft_word_- _02_-_our_first_program] , we made a windows program that uses a Windowsform. The form contains our controls including buttons with which the user can work with the program. We could also use this form to link (with a button) to other

    forms, providing for a starting point to access several parts of our program. We could to the same by inserting tabs or using a top side menu.

    In this 3rd post, we will approach this a little different.

    Our program - which will gain more functions in the future - will be used in a typical setting whereby the user works with Word, typing in documents. Part of our program will be fully automated document generation, but another part will be all about inserting of text blocks (fixed or completed with user input). We want to avoidthat the user has to open our program and keep it open as a windo w, but tucking it away only to revive it once in a while, when he wants to generate and insert text

    locks in his active document.

    Sounds confusing? Don't worry. It will be clear to you soon.

    What are we going to build?

    We are going to build a regular Windows application using a standard windows form. On this form, we will place and build a context menu (a menu that can havemultiple layers). Now, instead of running this form upon start up in the regular manner, we will tell Windows to start it minimized and to only show an icon in theWindows tray. Our aim is to let the user open our context menu by right clicking the icon in the tray. Exactly the behavior we are looking for in order to let our user have easy access to all our - soon to build - Word automation power.

    The steps to make it happen

    Step 1

    First, we start Visual Studio and start a new project (you can download Visual Studio Express for Desktop for free here [http://www.visualstudio.com/en-us/downloads/] -requires a Windows live/hotmail account -). It all starts by going to the top left screen and accessing the 'File' tab.

    Step 2

    http://www.visualstudio.com/en-us/downloads/http://www.devtome.com/http://www.visualstudio.com/en-us/downloads/http://www.devtome.com/http://www.devtome.com/doku.php?id=programming_microsoft_word_-_02_-_our_first_program

  • 8/19/2019 Programming Word - 1st Edition (2014)

    18/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 2/12

    Go from File → New Project.

    Step 3

    In the window that pops up, select Visual Basic → Windows on the left side and choose 'Windows Forms Application. You can use the name suggested in theillustration or choose your own name. Click 'OK'.

    Step 4

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    19/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 3/12

    Just as a standard operation, we rename the form's visible name from “Form1” to something more applicable. Make sure you select the form with a mouse click so youcan look up the 'Text' property in the 'Properties' window.

    Step 5

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    20/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 4/12

    Next, from the 'Toolbox' on the left, select and drag the NotifyIcon to the form.

    Step 6

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    21/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 5/12

    If done right, the NotifyIcon will show up as 'NotifyIcon1' in the lower part of the form's design window. This will happen if you drop a control onto the form that doesnot show on the form (e.g., a database control or this notifyicon control).

    Step 7

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    22/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 6/12

    Now, we will insert some code to tell the program to minimize the form from start. Double click the form in the design view (please ignore the 'ContextMenuStrip1 inthe picture, we will get to that in a moment).

    Step 8

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    23/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 7/12

    Double clicking the form will bring the code behind the form. Please note the line on top at the end. the 'Load' element in Mybase.Load tells the program to dosomething when the form is loaded. Since we want the form to minimize on start, that is exactly where we want to add code. Take over the code shown in theillustration and make sure that it is placed between the Private Sub Form 1 … and End Sub.

    In code:

    Me.WindowState = FormWindowState.MinimizedMe.ShowInTaskbar = False

    With notifyIcon1.Icon = Me.Icon.Visible = True.Text = "Task Tray"End With

    This is the code that makes the program behave like we want. Start minimized and show an icon in the task tray. The only thing left to do is building a menu andenabling access through the icon in the task tray.

    Step 9

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    24/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 8/12

    Select and drag the control 'ContextMenuStrip' from the Toolbox on the left to the form. If you cannot find the ContextMenuStrip, please make sure that you expand'All Windows Forms' in the Toolbox.

    Step 10

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    25/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 9/12

    If done right, a 'ContextMenuStrip1' will appear next to the NotifyIcon1 in the form's design view. In the form itself, a ContextMenuStrip is added in which you can fillin menu strips, both in the main strip as in sub strips. Please finalise the strip as you deem fit.

    Step 11

    This is my example of filling out the menu strip. This is the menu your user will see and work with. Therefore, make sure that the menu items are descriptive andlogical.

    Step 12

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    26/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 10/12

    Hang on, we are almost there. You have build the menu, but the menu needs to be accessible from the task bar. We will do this by manipulating a property of thenotifyicon. Select the 'NotifyIcon1' and look for the property 'ContextMenuStrip' in the Properties window. You can select the down arrow and choose theContextMenuStrip1 we just dragged onto our form.

    Now, this menu is accessible with a right click of the mouse on the task tray icon.

    Step 13

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    27/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 11/12

    Finally, we want to attach actions to the various menu items. We will not do this in this post; this is reserved for the next post where we will start to work on the firstelements of our Word automation code. Just to finalize this post, we will add code so the user can exit the program via the menu.

    For this purpose, we add an 'exit' element to the menu's main part.

    Step 14

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    28/153

    2/24/2015 programming_microsoft_word_-_03_-_run_program_from_the_tray - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray 12/12

    Double click the 'Exit' menu item, so Visual Basic brings you to the code section. Please note the end of the top line. The 'Click' item of theExitToolstripMenuItem.Click phrase tells us that the code we will insert, will be executed upon a 'click' on the Exit part of our menu. Exactly what we want.

    The code itself is simple. Just add 'End' telling the program to stop execution and terminate.

    Step 15

    The end result: an icon in the task tray, complete with several layers of menu. Very easy for a user to access when working on a Word document for a quick dose of Word Automation.

    We are now in an excellent position to start writing the first part of the actual Word automation elements. In the next post, we will build a simple form to insert thedetails of a party to a Word document.

    Computing A-Z | Programming | Software

    programming_microsoft_word_-_03_-_run_program_from_the_tray.txt · Last modified: 2014/08/20 17:06 by wekkelExcept where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported[http://creativecommons.org/licenses/by-sa/3.0/]

    Advertise with Anonymous Ads

    http://www.devtome.com/http://creativecommons.org/licenses/by-sa/3.0/http://www.devtome.com/http://www.devtome.com/doku.php?id=category:programminghttp://www.devtome.com/doku.php?id=start&do=recenthttp://www.devtome.com/doku.php?id=category:computinghttp://www.devtome.com/doku.php?id=category:softwarehttp://a-ads.com/?partner=5552

  • 8/19/2019 Programming Word - 1st Edition (2014)

    29/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 1/8

    ShapeShift Lens Plugin Send altcoins to any Bitcoin address online ShapeShift.io

    Ads by CoinURL

    Programming Microsoft Word - 04 - From Form to Word Document

    What are we going to do in this lesson?

    The purpose of this lesson is to create a windows form that will take user input and insert it in a Word document. One of the best aspects of software is its re-usability.Software code is just electronic text that can be reused over and over again. To demonstrate this feature, we will built on top of the application made in the previous.

    First, we are going to save our previous program as a template. If you have not built the program from the previous lesson [http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_tray] , do so now before proceeding.

    In the first steps, we are going to reopen our tray-application and save it as a template. From then on, this template will be available for reuse in future lessons.

    Step 1

    Fire up Visual Studio and open your tray application from the previous lesson [http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_- _run_program_from_the_tray] . Do so by opening via the menu: File → Open Project.

    Now, select your tray application built in the previous lesson and open the project.

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_trayhttp://www.devtome.com/doku.php?id=programming_microsoft_word_-_03_-_run_program_from_the_trayhttp://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    30/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 2/8

    Once you have opened the tray application, you export this project as a template (I assume you have build/run the tray application at least once already). Export it as atemplate through: File → Export Template.

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    31/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 3/8

    A window pops up with the question to choose a template type. I suggest you choose 'Project template' for now and click 'Next'. Leave everything as it is in thefollowing window (not shown below) other than choosing a relevant Template name and a proper Template description if you want. Then click 'Finnish'

    Okay, you did it. Your template is ready for the next part of this tutorial.

    Step 2

    In the following step, you are going to use your freshly created template to make an application based on that template. That will save you from building the trayapplication from scratch so we can get right to the Word automation part. Great, isn't it?

    Go to: File → New Project and search for your new template (example shown below).

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    32/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 4/8

    Select the template and create your new project. As you can see, the tray application is already present in your new project. That saves a lot of time coding the trayapplication from scratch!

    Step 3

    Depending on where you finished with the original tray application before you made the template, there is an extra step involved. We want to be sure that the trayapplication has an actual menu. If your application already has a menu, goto step 4 below. Otherwise, proceed as follows. Make sure that the form is visible by doubleclicking on Form.vb (or whatever the name of your form is) in the Solution Explorer. Now click on the ContextMenuStrip1 item (see picture below).

    The context menu appears in the design view of the form. Make sure to create at least one menu item. Making menu items is fairly intuitive in Visual Studio so I will

    let you work this out yourselves. When done, test the menu by running the application. If you did things right, an icon will appear in the tray that will show your menustructure when right-clicked. If so, you are ready for the next step.

    Step 4

    The next few steps will be about showing a new form when the user clicks an item of the tray menu system and building some routine in that new form to show Wordautomation in action. First, we will create the new form.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    33/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 5/8

    Right-click on the application's name in the solution explorer. Through the menu that appears, goto: Add ⇒ Windows Form.

    Choose a name for the new form. I simply chose form2.vb (the default name presented) and click 'Add'. A new form is added to your project and a form2.vb is shownin design view. Now, switch back to form1.vb and click the ContextMenuStrip1 again. The context menu strip appears on the form again.

    In my example, I go to one of the sub menu's created and I double click on one of the items (see picture). You can do the same with one of your own menu items youcreated earlier.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    34/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 6/8

    Double clicking the menu item of the context menu strip brings you to the code editor. Don't worry, the next step is very easy.

    Step 5

    When the user clicks that menu item, we want to show the new form (form2) we just created. That's easy. Just insert the following code:

    Form2.Show()

    That's it! Run the application and test it by clicking the relevant menu item from the tray application. Your new Form2 will be shown.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    35/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 7/8

    Step 6

    Before we move to the Word automation part, we are going to set up the form (form2). The user will provide input by means of text boxes on the form that will capturethat input. Go to the form again in Visual Studio.

    Make sure that the toolbox is shown on the left side of the Visual Studio program. With the little ping on top of the toolbox window, you can pin the toolbox so that itremains open on the left side (the left side is the default view of the toolbox in Visual Studio). Now, place one button on the lower right side of the form and add 4textboxes, arranged in rows. Do so by either dragging these elements from the toolbox onto the form, or double click each item in the toolbox so they appear on theform. Rearrange as shown in the picture below. A smart tip is to create one textbox on the form, select it and dragging it while holding Ctrl. Visual Studio will thenmake a copy of the textbox, making it easy to create a lot of textboxes quickly.

    Step 7

    The final step before working on Word automation is a quick routine showing how the textboxes can help you capture input from the user. The textboxes on our formare named by default 'TextBox1' , 'TextBox2', 'TextBox3' and 'TextBox4'. You are going to write code to capture any text input from those textboxes and show thisinput through a standard popup message window.

    First, click the button and you are taken to the code behind the button. Insert the following code between the 'Private Sub' and 'End Sub': Private SubButton1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    MsgBox("This is the contents of Textbox 1: " & TextBox1.Text & vbCrLf _ & "This is the contents of Textbox 2: " & TextBox2.Text & vbCrLf _ & "This is the contents of Textbox 3: " & TextBox3.Text & vbCrLf _ & "This is the contents of Textbox 4: " & TextBox4.Text) End Sub

    Now, run the program, bring up form2, type some text the four textboxes and hit the button. The messagebox shows the contents of the textboxes.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    36/153

    2/24/2015 programming_microsoft_word_-_04_-_from_form_to_word_document - Devtome

    http://www.devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document 8/8

    We will use this method in a similar manner in our first Word automation program. That will be covered in the next tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_ii] .

    Computing A-Z | Programming | Software

    programming_microsoft_word_-_04_-_from_form_to_word_document.txt · Last modified: 2014/08/20 17:02 by wekkelExcept where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported[http://creativecommons.org/licenses/by-sa/3.0/]

    Every 15 minutes 3000 satoshiClaim in XAPO Wallet

    motherfaucet.com

    Advertise with Anonymous Ads

    http://www.devtome.com/doku.php?id=category:softwarehttp://www.devtome.com/doku.php?id=category:programminghttp://www.devtome.com/http://creativecommons.org/licenses/by-sa/3.0/http://a-ads.com/?partner=5552http://www.devtome.com/doku.php?id=category:computinghttp://www.devtome.com/doku.php?id=start&do=recenthttp://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_ii

  • 8/19/2019 Programming Word - 1st Edition (2014)

    37/153

    2/24/2015 programming_microsoft_word_-_05_-_from_form_to_word_document_ii - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_i i 1/6

    VirWoX Die Tauschbörse für virtuelle Währungen. www.virwox.com

    Ads by CoinURL

    Programming Microsoft Word - 05 - From Form to Word Document (II)

    hat are we going to do in this tutorial?

    n the previous tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document] , we managed to take the tray

    application from tutorial 3, expand on it by building a second windows form and use textboxes on that new form to capture input from a user. The purposeof this tutorial is to direct this input to a Word document instead of the message box of the previous tutorial.

    ecause the interaction between your program and Windows Word requires some background information, I decided to dedicate a separate tutorial to theagic behind all this. Once you get this up and running, it's easy, but for future ease of use is vital to understand the basics behind it. I assume you have a

    copy of Office (2003 or upwards) installed on your PC.

    Ste p 1

    efore we go on with the program from the previous tutorial, you are first going to create a new project called 'MyFirstWordApp'. To do so, start Visualtudio and go to: File → New Project and choose Windows Forms Application. Set the name of the project to 'MyFirstWordApp'. Moving forward quickly,lace a textbox on the form and a button. Your screen will look like this:

    Step 2

    efore we add code, we need to make our program aware of the programming language necessary to manipulate Word documents. We will do so now.

    n the top menu of Visual Studio, go to: Project → Add Reference

    http://www.devtome.com/http://www.devtome.com/http://devtome.com/doku.php?id=programming_microsoft_word_-_04_-_from_form_to_word_document

  • 8/19/2019 Programming Word - 1st Edition (2014)

    38/153

    2/24/2015 programming_microsoft_word_-_05_-_from_form_to_word_document_ii - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_i i 2/6

    n the 'Reference Manager' window that pops up, we are looking for the COM list. Click the COM element on the left and a large list of references appears.e are looking for the 'Microsoft Office 12.0 Object Library'. The version number 12.0 indicates that I am using Office 2007. Other versions of Office will

    ender other version numbers for the relevant library (For instance, Office 2003 is 11.0). Just choose the version that is offered in your case.

    inding this library is easier by looking it up through the search window at the top-right (see picture below). Click and select 'Microsoft Office 12.0 Objectibrary' (or your version of this Object library.

    e want to add reference to another library: the 'Microsoft Word 12.0 Object Library'. Again, the version shown in your window may be different,depending on your Office version. Select the 'Microsoft Word 12.0 Object Library' and click OK.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    39/153

    2/24/2015 programming_microsoft_word_-_05_-_from_form_to_word_document_ii - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_i i 3/6

    dding reference is not visible in your code. However, it is a vital step to ensure that your program can 'talk' to Word. We are going to insert another eference, but now in our code. In the top of the form's code (so not the design view but the code behind the form), above the line 'Public Class Form1',nsert the following code:

    Imports Word = Microsoft.Office.Interop.Word

    ou will find out later on that this enables a reference to the Word object model through the statement 'Word' in your code.

    Step 3

    ow it is time to start with some real coding. In the design view, double click on the button; Visual Studio will bring your cursor between the lines 'Privateub Button1_Click' and 'End Sub'.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    40/153

    2/24/2015 programming_microsoft_word_-_05_-_from_form_to_word_document_ii - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_i i 4/6

    nter the following code:

    Dim wdApp As New Word.Application Dim wdDoc As Word.Document

    'This code will start Word and open a new document 'from the standard template. If an error occurs, the program 'throws a message Try wdDoc = wdApp.Documents.Add() wdApp.Visible = True Catch ex As Exception MsgBox("Error creating Word document.") End Try

    'With this line of code, the text in the textbox will be inserted 'at the place of the cursor in word wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)

    'cleaning up wdApp = Nothing

    his code starts with declaring two variables that will deal with two objects: the Microsoft Word program itself and a Microsoft Word document (the linesstarting with 'Dim'). By doing so, your program has an object to work with (either a Word document or Word itself).

    econd, the code declares a Word Document (wdDoc) and ask to 'Add' a document (wdApp.Documents.Add() ). To make sure that the Word application isisible to the user, the wdApp.Visible is set to true. This block of code is placed between a Try… Catch ex … End Try construction. This is done to avoidhe program crashing if the user has no Microsoft Word installed. The 'Exception' will then lead to a message box appearing with an error notice.

    hen the actual code to write text in a Word document. The program has already opened Microsoft Word and opened a blank document. The linewdApp.ActiveWindow.Selection.TypeText' tells the program a couple of things. ActiveWindow is the window active when the code runs. Selection isasically the place were the cursor is; in our case the start of a blank Word document. Then the command that actually 'types' text. Hence 'TypeText'. Theext to be typed is taken from the Textbox1 (Textbox1.Text in the code).

    he final line of code is about cleaning up. The object wdApp is set to nothing.

    ow, run the program, type some text in the textbox and hit that button. Voila, your text appears in a blank Word document

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    41/153

    2/24/2015 programming_microsoft_word_-_05_-_from_form_to_word_document_ii - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_i i 5/6

    problem appears

    eep the program running and try another line. And then insert a third line of text and hit that button again. You will have three Word documents open,showing the lines you just inserted in your program one by one.

    owever, there is a problem hidden in the dark. Each time your program 'adds' a Word document, it opens a new instance of Word. Consequently, you nowave 3 instances of Microsoft Word running. Start the task manager via Ctrl-Alt-Del and look at the programs running. You will find three Word programsWinword.exe) running instead of one (see picture).

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    42/153

    2/24/2015 programming_microsoft_word_-_05_-_from_form_to_word_document_ii - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_i i 6/6

    our user will find out that there is a problem when he closes a Word instance. Because there are more than one Word instances running, these instancesill interfere with each other and render akward error notices.

    ord is capable of opening multiple documents within one instance of the Word program running. We have to fix our code to check whether an instance of ord is already running before opening a new instance. We are going to to this in the next tutorial [http://devtome.com/doku.php?

    d=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way] .

    omputing A-Z | Programming | Software

    programming_microsoft_word_-_05_-_from_form_to_word_document_ii.txt · Last modified: 2014/08/28 16:38 by wekkelExcept where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-Share Alike 3.0 Unported[http://creativecommons.org/licenses/by-sa/3.0/]

    Withdraw Bitcoin and Litecoin to Debit Cards!

    247Exchange.com Regulated Bitcoin Exchangewww.247exchange.com

    Advertise with Anonymous Ads

    http://devtome.com/doku.php?id=category:computinghttp://a-ads.com/?partner=5552http://devtome.com/doku.php?id=start&do=recenthttp://creativecommons.org/licenses/by-sa/3.0/http://www.devtome.com/http://www.devtome.com/http://devtome.com/doku.php?id=category:softwarehttp://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_wayhttp://devtome.com/doku.php?id=category:programming

  • 8/19/2019 Programming Word - 1st Edition (2014)

    43/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 1/7

    Programming Microsoft Word - 06 - Creating WordDocuments the Right Way

    What are we going to do in this tutorial?

    In the previous tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_ii] ,we managed to place text from a textbox in our program in a Word document. However, we encountered a problem: our

    program does not take into account that one Word instance (the program Microsoft Word) can handle multiple documents atonce. Our code does not know that and faithfully opens a new instance of Word each time the program runs the code. TheseWord instances (visible as 'Winword.exe' in the task manager) interfere with each other and confuse your user. Time to getrid of that problem!

    Basi cally, we are going to teach our program to look for a instance of Word alr eady running. If so, the program will 'catch'that running instance and start working with it. If no instance of Word is runnin g yet, our program will start a new instance.Let's delve into the code.

    Step 1

    You will continue with the 'MyFirstWordApp' program from the previous tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_ii] . You are going to change the code that's behindButton 1. The procedure for checking whether Word is running is courtesy of Cindy Meister. Please

    Change the co de between “Private Sub Button1_Click(sender As Object, e As EventAr gs) Handles Button1.Click” and “EndSub” as follows:

    Dim wdApp As New Word.Application Dim appName As String = "Word.Application"

    'this code was created by Cindy Meister of Microsoft Dim wdProcesses() As System.Diagnostics.Process = _ System.Diagnostics.Process.GetProcessesByName("winword") Dim wdprocess As System.Diagnostics.Process For Each wdprocess In wdProcesses System.Diagnostics.Debug.Print(wdprocess.MainWindowTitle) System.Diagnostics.Debug.Print(wdprocess.StartInfo.Arguments.Length.ToString()) Next If wdProcesses.Length > 0 Then wdApp = System.Runtime.InteropServices.Marshal.GetActiveObject(appName) Else wdApp = New Word.Application End If 'end of code from Cindy Meister

    'create the Oject 'Word document' Dim wdDoc As Word.Document

    'This code will start Word and open a new document 'from the standard template. If an error occurs, the program 'throws a message Try

    wdDoc = wdApp.Documents.Add() wdApp.Visible = True Catch ex As Exception MsgBox("Error creating Word document.") End End Try

    http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_iihttp://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_iihttp://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_iihttp://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_iihttp://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_ii

  • 8/19/2019 Programming Word - 1st Edition (2014)

    44/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 2/7

    'With this line of code, the text in the textbox will be inserted 'at the place of the cursor in word wdApp.ActiveWindow.Selection.TypeText(TextBox1.Text)

    'cleaning up wdApp = Nothing

    Let's run through the mechanics of the first part of the new code. An object of a Word app is created and the program is toldto hold a string called 'Word.Application' in memory. The reason to keep this line in memory is to check whether an instanceof Word is already running.

    The next few lines of code create the objects 'wdProcesses' and 'wdprocess'. The program checks whether winword isrunning.

    If so, the program is not asked to start a new instance of Word. Instead, our Word program object (wdApp) is attached to therunning instance of Word by the 'GetActiveObject' command.

    If Winword is not running (the number of processes called 'winword' is zero), your program will start a new instance of Word.

    The rest of the program is basically the same as in the previous tutorial.

    Step 2

    Now that this technical issue has been solved, let's take the program one step further. A Word automation program may haveto interact with Word several times at different places in the code. You do not want to copy/paste the procedure each timethe program has to interact with Word. Instead, this code will be written once and called upon each time you need it.

    Let's get to work.

    First, delete all code between “Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click” and“End Sub”. You can switch to this code easily if you click on the button in form1 in the Design view.

    http://www.devtome.com/http://www.devtome.com/http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    45/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 3/7

    Step 3

    Now, add a new class to your solution. Right-click the solution in the Solution Explorer and choose Add → Class.

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    46/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 4/7

    In the next window, choose 'Class' and name the class 'WordActions' and click 'Add'.

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    47/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 5/7

    Step 4

    Place the following code in the new WordActions class (and don't forget to insert the line “Imports Word =Microsoft.Office.Interop.Word” at the top of the class). Place it between the blocks 'Public Class WordActions' and 'EndClass'.

    Public Shared Function NewWordDoc() 'Procedure NewWordDoc() ' '1. check whether Word is running '2. if so, open a new document '3. if not, start word and open new document ' 'Code to check whether Word is running 'courtesy of Cindy Meister, VSTO/Word MVP

    Dim oWord As Word.Application Dim oDoc As Word.Document Dim appName As String = "Word.Application" Dim wdProcesses() As System.Diagnostics.Process = _ System.Diagnostics.Process.GetProcessesByName("winword") Dim wdprocess As System.Diagnostics.Process

    For Each wdprocess In wdProcesses System.Diagnostics.Debug.Print(wdprocess.MainWindowTitle) System.Diagnostics.Debug.Print(wdprocess.StartInfo.Arguments.Length.ToString()) Next

    'If Word is running, attach oWord to that instance of Word If wdProcesses.Length > 0 Then oWord = System.Runtime.InteropServices.Marshal.GetActiveObject(appName)

    'if Word is not running, start new instance of Word Else oWord = New Word.Application End If

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    48/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 6/7

    If Not oWord Is Nothing Then oWord.Visible = True oWord.Activate()

    End If

    oWord.Visible = True

    'open new Word document based on the basic template oDoc = oWord.Documents.Add

    'Don't know what it does but by doing so, I'avoid a warning in Visual Studio about possibly 'no returning a value on all code paths Return oWord

    oDoc = Nothing oWord = Nothing

    End Function

    This code contains the routine that checks whether an instance of Word is already running. If so, it just creates a newdocument and if not, a new instance of Word is started and creates a new document. The code is ready for use in our form.

    Step 5

    Switch back to the code for Form1. Double click the button on this form to go to the code behind the button. Insert thefollowing line.

    This code refers to the WordActions class and the procedure (Function) in that class called NewWordDoc. Visual Studioinserts the () automatically.

    Now, run the program. When clicking the button on the form, a new Word document is created. Click the button again, andagain a new button is created. With the simple command 'NewWordDoc', your program creates a new document while thecode to do so is centrally available in the WordActions class. Powerful stuff.

    We are going to expand on this in the next tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_07_- _reusing_your_code] by adding extra code to insert text in a Word document, all this while keeping code centrally located inthe WordActions class.

    Computing A-Z | Programming | Software

    programming_microsoft_word_-_06_-_creating_word_docs_the_right_way.txt · Last modified: 2014/08/20 16:59 bywekkel

    http://devtome.com/doku.php?id=category:softwarehttp://www.devtome.com/http://devtome.com/doku.php?id=category:computinghttp://devtome.com/doku.php?id=category:programminghttp://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code

  • 8/19/2019 Programming Word - 1st Edition (2014)

    49/153

    2/24/2015 programming_microsoft_word_-_06_-_creating_word_docs_the_right_way - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way 7/7

    Except where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-ShareAlike 3.0 Unported [http://creativecommons.org/licenses/by-sa/3.0/]

    Advertise with Anonymous Ads

    http://creativecommons.org/licenses/by-sa/3.0/http://a-ads.com/?partner=5552http://devtome.com/doku.php?id=start&do=recent

  • 8/19/2019 Programming Word - 1st Edition (2014)

    50/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 1/7

    Programming Microsoft Word - 07 - Reusing Your Code

    What are we going to do in this tutorial?

    In the previous tutorial [http://devtome.com/doku.php?id=pro gramming_microsoft_word_-_06_-_creating_word_docs_the_right_way] ,we took away the problem of more than one instance of Word running while running your code over and over again. Theroutine to avoid this from happening is fairly complex and long. In this new tutorial we are going to break up the code somemore, so the block of code to open a new Word document can be reused multiple times.

    We are going to build on top of the 'MyFirstWordApp' from tutorial 5 [http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_ii] that was enhanced in tutorial[http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way] . If you do not have this

    project available, please go through the previous two tutorials to create that program.

    Step 1

    Open the 'MyFirstWordApp' program as you left it in the previous tutorial: File → Open Project → [choose relevant .slnfile]

    Ste p 2

    The design of Form1 will remain the same.

    However, we are going to change the code behind 'Button1'. First, we are going to add a new class to our project. In theSolution Explorer, right-click the project and move through the menu that appears: Add → Class

    http://www.devtome.com/http://www.devtome.com/http://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_wayhttp://www.devtome.com/http://devtome.com/doku.php?id=programming_microsoft_word_-_05_-_from_form_to_word_document_iihttp://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_wayhttp://devtome.com/doku.php?id=programming_microsoft_word_-_06_-_creating_word_docs_the_right_way

  • 8/19/2019 Programming Word - 1st Edition (2014)

    51/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 2/7

    Name the new class 'Wordactions.vb'.

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    52/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 3/7

    Step 3

    If your new class is not shown yet in the code editor, double click the new WordActions class in the Solution Explorer. First,insert a reference to Word Interop.

    Second, create a Function called 'NewWordDoc' by inserting the following code between 'Public Class WordActions' and'End Class'.

    Public Shared Function NewWordDoc(oWord As Word.Application) As Word.Application 'Procedure NewWordDoc() ' '1. check whether Word is running '2. if so, open a new document '3. if not, start word and open new document ' 'Code to check whether Word is running 'courtesy of Cindy Meister, VSTO/Word MVP

    Dim oDoc As Word.Document Dim appName As String = "Word.Application" Dim wdProcesses() As System.Diagnostics.Process = _

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    53/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 4/7

    System.Diagnostics.Process.GetProcessesByName("winword") Dim wdprocess As System.Diagnostics.Process

    For Each wdprocess In wdProcesses System.Diagnostics.Debug.Print(wdprocess.MainWindowTitle) System.Diagnostics.Debug.Print(wdprocess.StartInfo.Arguments.Length.ToString()) Next

    'If Word is running, attach oWord to that instance of Word If wdProcesses.Length > 0 Then oWord = System.Runtime.InteropServices.Marshal.GetActiveObject(appName)

    'if Word is not running, start new instance of Word Else oWord = New Word.Application End If

    If Not oWord Is Nothing Then oWord.Visible = True oWord.Activate()

    End If

    oWord.Visible = True

    'open new Word document based on the basic template

    oDoc = oWord.Documents.Add

    'Don't know what it does but by doing so, I'avoid a warning in Visual Studio about possibly

    'no returning a value on all code paths Return oWord

    oDoc = Nothing oWord = Nothing

    End Function

    There are a couple of things different in this code than in the code from tutorial 6. We will run through this later in thistutorial to show the differences.

    Third, insert another block of code between 'Public Class WordActions' and 'End Class' (I suggest placing it below the NewWordDoc function just created).

    This WordActions class contains code that we can reuse over and over again in our project. This saves time and avoidsunnecessary bugs. Furthermore, updating code becomes easier. Now, we will look at the code behind 'Button1'.

    Step 4

    Double click on the Button1 in Form1 in the design view.

    Now, please update the code between 'Private Sub Button1_Click …' and 'End Sub' to read like this:

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    54/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 5/7

    Now, test your application by running it, placing text in the textbox and hitting Button1.

    And it is working fine:

    In the paragraphs below, we will run through this new code to get a better idea how the code works.

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    55/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 6/7

    Reviewing the code closer

    Let's take a closer look at what happens when the user clicks the button. My explanation is not very technical. I just try tomake some sense in what's happening so you get a basic understanding of what the code does. It all starts in Form1.

    First, there are to objects declared: oWord as Word application and Sel as Word selection. This is done because we needthose two objects later on in the code.

    Second, the text in the textbox1 on our form is placed in the variable 'iNsert'. After these variables have been declared, thecommand NewWordDoc is called. There are a few things happening here.

    1. the oWord variable is redefined as the 'outcome' or 'result' of the Function 'NewWordDoc'. Because this function islocated in the class 'Wordactions', it is typed as 'WordActions.NewWordDoc'.

    2. The addition of (oWord) at the end feeds the oWord object created in Form 1 to the NewWordDoc function in the classWordActions.

    When looking at the code for the function 'NewWordDoc' in the class 'WordActions', you will notice that the first linecontains a few particular elements.

    Public Shared Function NewWordDoc(oWord As Word.Application) As Word.Application

    'Public' and 'Shared' mean that this code is accessible and can be used in a certain way in your program, not only within theWordActions class itself. The Function description contains some additional input between the brackets. What we are tellingthe computer is that it should expect a Word Application object to be feeded into the function. In our case we feed it with

    'oWord' created in the Form1 code.The code after the brackets 'As Word.Application' is used to have this function return a Word application object. We passthis back to the Form1 code with the 'return oWord' command later in the 'NewWordDoc' code. We do this because we needthat oWord object in the next steps in Form1. The Word document created was created in the NewWordDoc function. Tomake this Word object - in the context of the NewWordDoc code attached to the actual Word application running - also

  • 8/19/2019 Programming Word - 1st Edition (2014)

    56/153

    2/24/2015 programming_microsoft_word_-_07_-_reusing_your_code - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code 7/7

    accessible to the code in Form1, the funciton returns this Word object (oWord) to the code in Form1. This may look confusing (and the computer being dumb), but this is a very essential element to make this code work. Please look at thisconcept closely and try to understand what is happening.

    After the NewWordDoc function has created a new Word document, the next line in the Form1 code gives the computer theassignment to place the text, held in the variable 'iNsert' (a string) into the Word document just opened. Lets take a closer look at this code in Form1.

    Sel = oWord.Selection

    Remember, we declared an object being a Word.Selection. Now, the selction (Sel) is set equal to the selection in the oWordobject which came out of the NewWordDoc function. Basically, this is the start of the newly created Word document. Thisenables the code to insert text at the cursor in the Word document. We look at this in closer detail in our review of the nextline of code.

    WordActions.TypeText(iNsert, Sel)

    Again, in the Form1 code reference is made to a command in the WordActions class. This time the 'TypeText' command iscalled. The TypeText command is completed with two elements between brackets. We feed this command with iNsert (astring) and the selection in the Word document (basically the place of the cursor).

    Public Shared Sub TypeText(ByVal text As String, ByRef Sel As Word.Selection)Sel.Text = textSel.Start = Sel.End

    Again, we see the 'Public' and 'Shared' attributes to a command. Because this command (also called a procedure) does notreturn anything, it is called a 'Sub' instead of a 'Function'. The Sub 'TypeText' has two parameters between the brackets: 1.'text' as a string (the line of text that we want typed in our document) and 2. 'Sel' as a word selection (the place of the cursor in the Word document). Subsequently, the command 'Sel.Text = text' is the actual command placing the text in the Worddocument. The next line 'Sel.Start = Sel.End' is used to make sure that the cursor in the actual Word document is set justafter the last character our program placed in the word document. This is handy if we have additional lines of code insertingadditional lines of text in the Word document.

    There is an easier way of typing text in the Word document created. Instead of the route via our WordActions.TypeTextroutine. you could also use the following code to insert text. Place this code in the Sub 'TypeText' in the WordActions classand see whether it works.

    Sel.TypeText(text)

    We could also insert this code in the Form1 code directly (change 'text' to 'iNsert' then), but that would defeat the purpose of showing reusing code in this tutorial :)

    This concludes this tutorial on reusing code. In the next tutorial, we will expand on reusing code a little bit.

    Computing A-Z | Programming | Software

    programming_microsoft_word_-_07_-_reusing_your_code.txt · Last modified: 2014/08/20 16:58 by wekkelExcept where otherwise noted, content on this wiki is licensed under the following license: CC Attribution-ShareAlike 3.0 Unported [http://creativecommons.org/licenses/by-sa/3.0/]

    Every 15 minutes 3000 satoshiClaim in XAPO Wallet

    motherfaucet.com

    Advertise with Anonymous Ads

    http://a-ads.com/?partner=5552http://devtome.com/doku.php?id=category:computinghttp://devtome.com/doku.php?id=start&do=recenthttp://creativecommons.org/licenses/by-sa/3.0/http://devtome.com/doku.php?id=category:softwarehttp://devtome.com/doku.php?id=category:programming

  • 8/19/2019 Programming Word - 1st Edition (2014)

    57/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 1/10

    Programming Microsoft Word - 08 - Populating a Word Document

    What are we going to do in this tutorial?

    In the previous tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code] , you tackled the topic of reusing code. This topic is notover by a long shot, but you covered some ground, enough to think about structuring your code to benefit from reusing code. In this tutorial, we move to the Word

    document itself. After all, the whole idea of this course is to automate the creation of Word documents.

    This tutorial covers two methods to insert input programmatically into a Word document; by using bookmarks and by using the 'find and replace' function of MicrosoftWord. You need to do two things for each method: prepare a suitable Word document and use specific code to fill in that Word document.

    Because two methods will be shown including preparation of the related Word documents, this tutorial will be quite large compared to the other tutorials. Althoughover lapping previous tutorials a bit, we are going to start from scrat ch.

    Step 1

    First, we are going to prepare 2 Word documents. The Word documents will be prepared as .dotx documents, meaning as a 'template'. We can build the two templatesfrom on Word document.

    Start Word and open a new Word document. Type the following text in the Word document.

    Now, replace the text with '**' (2 instances in the text) with '[name]' without the quotes. The [name] tag is plain text and this can be helpful as I will show later on.Time to save this document as our first template (I named the document 'FandR.Template.dotx (Find and Replace)). Saving the document as template is shown in the

    picture below.

    Office button → Save as → Save as template

    http://www.devtome.com/http://www.devtome.com/http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code

  • 8/19/2019 Programming Word - 1st Edition (2014)

    58/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 2/10

    You can build the 2nd template from the same document. We are going to insert bookmarks at the spots where the '[name]' tags are shown. Select the text of the first[name] tag with the cursor so that it is highlighted in blue. Under the Word Ribbon under Insert, there is a button 'bookmarks' under the 'links' section (see picture

    elow).

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    59/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 3/10

    When clicking the 'bookmark' button, the bookmarks windows that pops up shows a blank list of bookmarks. Just type the name of your first bookmark (I suggest'Name1') and press the 'Add' button. Close the bookmarks window and select the 2nd instance of '[name]' in your Word document. Again, press the bookmark button,type the name of the 2nd bookmark and press 'Add' (I suggest 'Name2'). You could actually name the 2nd instance of '[name]' Name1 as well, but then the 1st

    ookmark you created will be deleted. This is particular behaviour of bookmarks and you do not get a warning.

    http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    60/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 4/10

    Now that you have inserted 2 bookmarks in the Word document, save the document again as a template, but give it the name 'Bkm.Template.dotx'. You can close Wordnow.

    Step 2

    Time to fire up Visual Studio. I assume you already know your way around the Visual Studio Interface so we can quickly go through the first steps. Start a new project:File → new project → choose Windows Forms Application → give it the name 'InteropInsertTextinWordDoc'.

    Step 3

    You have to insert references to the Word object model (like you did in previous tutorials). Goto: Project → Add Reference → click the 'COM' tab → type 'Word' inthe search field. In my occassion, the search results in, inter alia, a reference to the Microsoft Word 12.0 Object Library. Depending on the Office/Word versioninstalled on your PC, the version number may vary. Select this library and add a reference to it by clicking 'OK'.

    One more thing to do before we start with some real programming. On top of the form1 insert the line 'Imports Microsoft.Office.Interop' as shown in the picture below.You can get to the code of the form by double clicking the graphic presentation of form1 in the Visual Studio IDE.

    Step 4

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    61/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 5/10

    Add the 2 Word templates you just created to your project. To do so, right-click the project name and go through the menu that appears: Add → Existing Item.

    In the resulting Dialog box, make sure to select 'All Files (*.*)' in the file name filter dialog box. Otherwise, your Word template documents won't show as selectablefiles.

    Go and find the location of the 2 Word templates you created in step 1. Add those 2 files to your project. You can see that the two files have been added to your project.If you save your project, you can actually find the 2 files in the project's file folder. They were copied into your project.

    Just to avoid any problems, make sure to set the properties for each file to 'Copy always' (see picture):

    http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    62/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 6/10

    Step 5

    Build Form 1 so it looks as shown below (1 textbox and 2 buttons).

    I did not change the default names for the labels, textboxes and buttons when creating these controls on the form.

    Step 6

    Now for the coding, this will get a little intense. You will code two procedures; one for each button. The first procedure will insert text at bookmarks in a Worddocument and the second procedure will insert text at name tags in a Word Document.

    Each procedure will use a separate procedure to open a Word template document. You will create this procedure in a separate class. The procedure to open this Wordtemplate (or better said: create a new Word document on the basis of a Word template) can subsequently be used by both main procedures. The strength of using aWord template is that the template itself is not opened, but instead, a new Word document will be opened (that the user can save, based on the chosen template).

    You will have to use the code from the previous tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code] , but then slightlychanged. You will have to code one block of code that opens a template. You can use that block of code for both main procedures.

    Right click on your project in the Solution Explorer and go through the menu: Add → Class

    http://www.devtome.com/http://www.devtome.com/http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code

  • 8/19/2019 Programming Word - 1st Edition (2014)

    63/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 7/10

    Name your class 'WordActions.vb' and press 'OK'. In the Solution Explorer, you will see your WordActions class added to your project.

    Double click the WordActions class in the Solution explorer to get to the code.

    On top of this class (above the start line 'Public Class WordActions'), add a reference: 'Imports Microsoft.Office.Interop' (see picture below).

    Create a new procedure in this class named 'OpenWordTemplate' (see picture below).

    http://www.devtome.com/http://www.devtome.com/http://www.devtome.com/

  • 8/19/2019 Programming Word - 1st Edition (2014)

    64/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 8/10

    Specifically note that you are going to feed this procedure with a 'doc' variable, explaining to this code which Word template to open. The function will return a Wordobject as well (the 'Word.Document')', so you can continue to work with the Word document just opened once the code execution returns to your Form1. This isexpressed by the final addition at the end of the Function's first line: ' Public Shared Function …… As Word.Document'). We are going to look into this a bit further

    elow.

    Enter the following code between the two lines 'Public Shared Function OpenWordTemplate( … ' and 'End Function'

    'Procedure OpenWordTemplate() ' '1. check whether Word is running '2. if so, create a new document based on the supplied doc variable (a Word template) '3. if not, start word and then create a new document based on the supplied doc variable (a Word template) '

    '====================================== 'Code to check whether Word is running 'courtesy of Cindy Meister, VSTO/Word MVP

    Dim oWord As Word.Application Dim oDoc As Word.Document Dim appName As String = "Word.Application" Dim wdProcesses() As System.Diagnostics.Process = _ System.Diagnostics.Process.GetProcessesByName("winword") Dim wdprocess As System.Diagnostics.Process

    For Each wdprocess In wdProcesses System.Diagnostics.Debug.Print(wdprocess.MainWindowTitle) System.Diagnostics.Debug.Print(wdprocess.StartInfo.Arguments.Length.ToString()) Next

    'If Word is running, attach oWord to that instance of Word If wdProcesses.Length > 0 Then oWord = System.Runtime.InteropServices.Marshal.GetActiveObject(appName) 'if Word is not running, start new instance of Word Else oWord = New Word.Application End If If Not oWord Is Nothing Then oWord.Visible = True oWord.Activate() End If oWord.Visible = True '======================================

    'open new Word document based on the basic template oDoc = oWord.Documents.Add(doc)

    Return oDoc oDoc = Nothing oWord = Nothing

    The first part of this code (between the '====' characters) deals with checking whether an instance of Microsoft Word is already running. We covered this code in the

    previous tutorial [http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code] . The next part of the code simply takes the value of the 'doc'ariable specified (the location of your Word template file) and opens this template as a new Word document (the command 'oDoc = oWord.Documents.Add(doc)').

    Note that the command 'Add' is used and not the command 'Open'. The command 'Open' would open the Word template file itself, which is not the behaviour we arelooking for.

    The line 'Return oDoc' is part of the cryptic explanation. As stated above, this Function is specified to 'return' a Word.Document. What this means is that the code inthis function in the WordActions class creates a new instance of a Word document (a Word object). That Word object (which includes the just opened Word document,the 'Word.Document' object) is returned to the Form1 code during execution.

    Step 7

    Now that you got the internals set up, it is time to check whether those internals work. Switch back to the code of Form1 and insert the following code (see pictureelow).

    Place the following code in the subroutine for Button1 (double click Button1 to get to the code section):

    Dim oDoc As Word.Document

    'open Word template based on the Bookmark Template oDoc = WordActions.OpenWordTemplate("Bkm.Template.dotx")

    'code to insert text at a bookmark in the opened Word template oDoc.Bookmarks("Name1").Range.Text = TextBox1.Text oDoc.Bookmarks("Name2").Range.Text = TextBox1.Text

    Button 1 is associated with inserting text into bookmarks. First, you define the variable 'oDoc' as placeholder for the Word document to be created. The command tocreate a new Word document on the basis of the Bkm.Template.dotx template (the function called 'OpenWordTemplate') is the function we created in the WordActionsclass. To access this function, we refer to the WordActions class before specifying this function. The name of our template 'Bkm.Template.dotx' is fed into this functionas parameter.

    The code to insert text at the bookmarks in the Word template is simple. The command 'oDoc.Bookmarks(”[name_of_bookmark”).Range.Text' takes the text specified(the text element of our textbox1) and places it as text in the Word document at the specified bookmark.

    This makes clear why it is important that the function to open the Word document (on the basis of the template returns that Word document to form1. Otherwise, thecode in form1 does not now which oDoc variable is specified when issuing the command to insert text in a bookmark.

    Run the code and press the first button (in my example named 'Insert @Bookmark'). Your Word template is opened as a new Word document. You can open moreWord documents based on the same template by pressing the button again. The template remains untouched; instead a new Word document is opened that a user canedit and save.

    http://devtome.com/doku.php?id=programming_microsoft_word_-_07_-_reusing_your_code

  • 8/19/2019 Programming Word - 1st Edition (2014)

    65/153

    2/24/2015 programming_microsoft_word_-_08_-_populating_a_word_document - Devtome

    http://devtome.com/doku.php?id=programming_microsoft_word_-_08_-_populating_a_word_document 9/10

    As a final conclusion of this step, insert the following code for Button 2 (double click Button2 to get to the code section):

    Dim oWord As Word.Application = Nothing

    'open Word template based on the Bookmark Template oWord = WordActions.OpenWordTemplate2("FandR.Template.dotx", oWord)

    'code to insert text at a bookmark in the opened Word template 'Find and replace tag [name] with input from textbox1

    Dim FindObject As Word.Find = oWord.Application.Selection.Find With FindObject .Clear