Solved

pass variables to a Word document

Posted on 2004-10-14
30
847 Views
Last Modified: 2012-06-21
I am writing a WinForms application in VB.Net.

Does anyone have some sample code for passing variables to a Word document?  I have read a multitude of links that Experts have recommended in the past, but I would like just a quick sample code snippet to achieve the following.

I have a 'standard' letter, which does not change except for the Name and Address of the recipient, which I would like to "pass" to the Word document from my application.  Of course I will also need to know what I need to type into the Word document in order for the application to recognise that this is where it must insert the variable being passed.

Some further issues:-

1.  Do I need to enter eg. <<AddressLine1>> in the word document  and then somehow detect and replace this from the application?

or

2.  Do I simply use bookmarks in Word and then simply say in the application: something like At bookmark "bookmark1" insert txtAddressLine1.text (say).

TIA    :-)
0
Comment
Question by:Sigh_Man
  • 14
  • 10
  • 6
30 Comments
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12307192
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12307256
In the second article, I tried to type in
"Imports Word = Microsoft.Office.Interop.Word" at the top of my Form, but it would not let me type past "Imports Word = Microsoft.Office."   The only option after Microsoft.Office was "Core", not "Interop".
Why is this?
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12307508
It depends on the version you have added in reference. Have you added Word to your references?
0
 
LVL 18

Expert Comment

by:mdougan
ID: 12308290
Hi Sigh_Man,

Yes, you want to create a document, typically, you'll fill in sample data for the stuff you want to overlay at run time... then, highlight, say, the person's name and create a bookmark, highlight their address and create a bookmark etc... once you have your document saved with all the bookmarks, then you can replace whatever text is in those bookmarks with whatever you pass from your program.  Then, it's important to save the file as a different filename, since you don't want to lose your "template" document.

Imports Microsoft.Office.Interop



    Public Function CreateWordDocument(ByVal sFileName As String) As Boolean

        Dim mAppPath As String
        Dim wordApp As New Microsoft.Office.Interop.Word.Application()
        Dim wordDoc As Word.Document
        Try

            mAppPath = System.Reflection.Assembly.GetExecutingAssembly.Location
            mAppPath = Microsoft.VisualBasic.Left(mAppPath, mAppPath.LastIndexOf("\")) & "\"

            wordApp.Visible = False
            wordDoc = wordApp.Documents.Open(mAppPath & "Formletter.doc")
 
            wordDoc.Bookmarks("memo_date").Range.Text = Now.ToShortDateString
            wordDoc.Bookmarks("customer_name").Range.Text = drLocal("customer_name")
            wordDoc.Bookmarks("customer_name2").Range.Text = drLocal("customer_name")

            wordDoc.Bookmarks("address1").Range.Text = drLocal("address_street")
            wordDoc.Bookmarks("address2").Range.Text = drLocal("address_street2")
            wordDoc.Bookmarks("city").Range.Text = drLocal("address_city")
            wordDoc.Bookmarks("state").Range.Text = drLocal("address_state")

            wordDoc.SaveAs(sFileName)
            CType(wordDoc, Microsoft.Office.Interop.Word._Document).Close(False)
            CreateWordDocument = True


        Catch x As Exception
            CreateWordDocument = False
            MsgBox(x.Message)
        Finally
            NAR(wordDoc)
            CType(wordApp, Microsoft.Office.Interop.Word._Application).Quit()
            NAR(wordApp)
            GC.Collect()
        End Try

    End Function

    Private Sub NAR(ByVal o As Object)
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(o)
        Catch x As Exception
            MsgBox(x.Message)
        Finally
            o = Nothing
        End Try
    End Sub



Cheers!
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12312186
MDougan -- that's cool, I'll try the sample code shortly...

emoreau:  >>It depends on the version you have added in reference. Have you added Word to your references?
Yes, I added  Microsoft Word 10.0 Object Library  (TypeLib Version 8.2)
Does this mean I should just add "Imports Word" since that was available from the Imports menu?
0
 
LVL 18

Expert Comment

by:mdougan
ID: 12312312
No, you should import either the Microsoft.Office.Core library, or the Interop library... by the way, if you're working with any of the Office programs through .NET, the Interop libraries that came with Visual Studio were outdated... and there was an upgrade to them that you could download from Microsoft... not sure if they are already included in later versions of Visual Studio or not... but Microsoft Strongly suggested upgrading the Interop libraries... (search their site for that)

Also, pay close attention to the way I'm calling the NAR function above... if you declare an Office type object like a Word document, your application will not deallocate the storage from the loaded COM component unless you call that code... setting your local variable = Nothing won't deallocate it as it would for a normal .NET object.
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12312362
MDougan,

When I type in your code, why does "wordDoc.Bookmarks" get the blue underline with the problem shown as "Interface 'Word.Bookmarks' cannot be indexed because it has no default property".
And do I need to replace 'drLocal' with something?

Thanks
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12312436
I cannot Import 'Interop' -- it's not one of the options available to me
0
 
LVL 18

Accepted Solution

by:
mdougan earned 250 total points
ID: 12312813
Well, a couple of things... first, you will need to add a "reference" to the Interop libarary in your project.. so, over in the project explorer, right-click on the folder that says References, and click on Add.... then, you'll probably need to click on the browse button...

Then, you're trying to browse to something called the Office.dll.... mine is located here:

C:\WINDOWS\assembly\GAC\Office\7.0.3300.0__b03f5f7f11d50a3a\Office.dll

That will add a reference called the Microsoft.Office.Core to your references.  Then, in your form/class module, you should add the Imports statement:

Imports Microsoft.Office.Interop

If you get an error on that, then you may need to download and install the Interop libraries from Microsoft...  try this link:

http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnoxpta/html/odc_oxppias.asp

You'll need to download oxppia.exe, this is the XP Interop Assemblies for Microsoft COM Office applications.  Extract these files to a directory on your computer and follow the instructions at the link above....

These files are necessary to do Office Automation without all the bugs you'll get otherwise.

That should register the Microsoft.Office.Interop in your GAC so that  your references should work.  I suspect that the problem you're getting with the bookmarks is because it doesn't know what a Bookmarks collection is, which it won't, as long as you are having problems referencing the Import statement, or any of the Office variables as I've declared them.

Next, just make sure that you've created your document with named bookmarks (you highlight some text and choose Insert Bookmark from the menu, and type in a name for the bookmark... then, you have to refer to that name in your code)

Yes, the dr("customer_name") etc in my code is where I'm getting the value that I want to put into the document... I'd opened a DataReader object and retrieved some data from the database... so, you'll have to figure out where you want to get your data from... for testing purposes, you can just do this:

           wordDoc.Bookmarks("memo_date").Range.Text = "10/13/2004"
            wordDoc.Bookmarks("customer_name").Range.Text = "Bob Smith"

assuming that you've created a bookmark called "memo_date"  and "customer_name"
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12318787
OK, I have now sorted the interop Import problem - this is what I have at the top of my form...

Imports Microsoft.Office.Interop
Imports Word
Public Class frmMainWindow
    Inherits System.Windows.Forms.Form


BUT, the problem with the blue underline is still happening.....

Dim mAppPath As String
        Dim wordApp As New Microsoft.Office.Interop.Word.Application
        Dim wordDoc As Word.Document

        Try
            mAppPath = System.Reflection.Assembly.GetExecutingAssembly.Location
            mAppPath = Microsoft.VisualBasic.Left(mAppPath, mAppPath.LastIndexOf("\")) & "\"
            wordApp.Visible = False
            wordDoc = wordApp.Documents.Open("C:\Documents and Settings\My Documents\VB\LetterheadWithBMs.dot")

            wordDoc.Bookmarks("TESTDATA").Range.Text = Now.ToShortDateString
            wordDoc.Bookmarks("TESTDATA2").Range.Text = ("Yes, it worked.")

The two bottom lines are underlined in blue at "wordDoc.Bookmarks".  Why is this happening?

:-(
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12318846
If you place the mouse pointer over the blue line (or if you look in the task list), you should see the reason why the line is in error. What is this reason?
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12318963
Interface 'Word.Bookmarks' cannot be indexed because it has no default property.
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12318965
Try this:

Dim oRng As Word.Range
oRng = oDoc.Bookmarks.Item("TESTDATA").Range
oRng.InsertAfter(Now.ToShortDateString)
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319163
Cool!!

But how do I replace the bookmarked text with the text from the application?
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12319191
Normally, bookmarks are initially empty!
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12319205
have you tried
oRng.Text(Now.ToShortDateString)
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319240
Ah right, fair point!   :D

Many thanks.
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319284
One last thing, do you know the code for replacing text in that Word document?

Eg, if I have a letter containing say  "<<NAME>>" and I want to replace <<NAME>> with "David" for example.
0
 
LVL 69

Assisted Solution

by:Éric Moreau
Éric Moreau earned 250 total points
ID: 12319306
Save a macro that will do a Find and replace. Look at the code generated by the macro recorder. It will be really close to what you need to do in VB.Net.
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319367
That's good enough for me.

Cheers!
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319499
Yes, I just tried

oRng.Text(Now.ToShortDateString)

and it didn't work.
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319633
Ignore me -- my mistake - it's working now.

Cheers
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12319657
Can you have Text inside a Bookmark? I don't think so. A Bookmark is a simple placeholder that allows you to position yourself at a specific point into a document. The template document should not contains text after bookmarks.
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12319711
Thanks for all your help.
0
 
LVL 18

Expert Comment

by:mdougan
ID: 12321697
emoreau, you can have text inside of a bookmark... that is how I like to define bookmarks... first, I type up my document with sample data as I would want it to appear, and then I highlight various pieces of sample text (say City or State or Zip) and choose Insert Bookmark.  All the text highlighted becomes part of the bookmark, and when you do the:

wordDoc.Bookmarks("TESTDATA2").Range.Text = ("Yes, it worked.")

Any text inside of the bookmark gets replaced if you specify the Range.Text
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12321739
Good to know. I have always used bookmarks as placeholder and used InsertAfter which caused me problems in the past. I will surely change my method for next projects.

Do you know if the range is keeping its settings (bold, underline, ...) when you replace the Text?
0
 
LVL 18

Expert Comment

by:mdougan
ID: 12321980
I believe so, which is why I prefered to do it this way... I couldn't set an attribute without there being text there.
0
 
LVL 1

Author Comment

by:Sigh_Man
ID: 12323344
Thanks guys for all your help.  I hope you're OK with the points split.

Cheers      :D
0
 
LVL 69

Expert Comment

by:Éric Moreau
ID: 12323394
No problem!
0
 
LVL 18

Expert Comment

by:mdougan
ID: 12323466
No problem here either :)
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

It’s quite interesting for me as I worked with Excel using vb.net for some time. Here are some topics which I know want to share with others whom this might help. First of all if you are working with Excel then you need to Download the Following …
The ECB site provides FX rates for major currencies since its inception in 1999 in the form of an XML feed. The files have the following format (reducted for brevity) (CODE) There are three files available HERE (http://www.ecb.europa.eu/stats/exch…
It is a freely distributed piece of software for such tasks as photo retouching, image composition and image authoring. It works on many operating systems, in many languages.
This video shows how to remove a single email address from the Outlook 2010 Auto Suggestion memory. NOTE: For Outlook 2016 and 2013 perform the exact same steps. Open a new email: Click the New email button in Outlook. Start typing the address: …

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now