Link to home
Start Free TrialLog in
Avatar of Sigh_Man
Sigh_Man

asked on

pass variables to a Word document

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    :-)
Avatar of Éric Moreau
Éric Moreau
Flag of Canada image

Avatar of Sigh_Man
Sigh_Man

ASKER

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?
It depends on the version you have added in reference. Have you added Word to your references?
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!
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?
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.
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
I cannot Import 'Interop' -- it's not one of the options available to me
ASKER CERTIFIED SOLUTION
Avatar of mdougan
mdougan
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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?

:-(
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?
Interface 'Word.Bookmarks' cannot be indexed because it has no default property.
Try this:

Dim oRng As Word.Range
oRng = oDoc.Bookmarks.Item("TESTDATA").Range
oRng.InsertAfter(Now.ToShortDateString)
Cool!!

But how do I replace the bookmarked text with the text from the application?
Normally, bookmarks are initially empty!
have you tried
oRng.Text(Now.ToShortDateString)
Ah right, fair point!   :D

Many thanks.
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.
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
That's good enough for me.

Cheers!
Yes, I just tried

oRng.Text(Now.ToShortDateString)

and it didn't work.
Ignore me -- my mistake - it's working now.

Cheers
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.
Thanks for all your help.
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
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?
I believe so, which is why I prefered to do it this way... I couldn't set an attribute without there being text there.
Thanks guys for all your help.  I hope you're OK with the points split.

Cheers      :D
No problem!
No problem here either :)