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 :-)
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 :-)
ASKER
In the second article, I tried to type in
"Imports Word = Microsoft.Office.Interop.W ord" 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?
"Imports Word = Microsoft.Office.Interop.W
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.W ord.Applic ation()
Dim wordDoc As Word.Document
Try
mAppPath = System.Reflection.Assembly .GetExecut ingAssembl y.Location
mAppPath = Microsoft.VisualBasic.Left (mAppPath, mAppPath.LastIndexOf("\")) & "\"
wordApp.Visible = False
wordDoc = wordApp.Documents.Open(mAp pPath & "Formletter.doc")
wordDoc.Bookmarks("memo_da te").Range .Text = Now.ToShortDateString
wordDoc.Bookmarks("custome r_name").R ange.Text = drLocal("customer_name")
wordDoc.Bookmarks("custome r_name2"). Range.Text = drLocal("customer_name")
wordDoc.Bookmarks("address 1").Range. Text = drLocal("address_street")
wordDoc.Bookmarks("address 2").Range. Text = drLocal("address_street2")
wordDoc.Bookmarks("city"). Range.Text = drLocal("address_city")
wordDoc.Bookmarks("state") .Range.Tex t = drLocal("address_state")
wordDoc.SaveAs(sFileName)
CType(wordDoc, Microsoft.Office.Interop.W ord._Docum ent).Close (False)
CreateWordDocument = True
Catch x As Exception
CreateWordDocument = False
MsgBox(x.Message)
Finally
NAR(wordDoc)
CType(wordApp, Microsoft.Office.Interop.W ord._Appli cation).Qu it()
NAR(wordApp)
GC.Collect()
End Try
End Function
Private Sub NAR(ByVal o As Object)
Try
System.Runtime.InteropServ ices.Marsh al.Release ComObject( o)
Catch x As Exception
MsgBox(x.Message)
Finally
o = Nothing
End Try
End Sub
Cheers!
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.W
Dim wordDoc As Word.Document
Try
mAppPath = System.Reflection.Assembly
mAppPath = Microsoft.VisualBasic.Left
wordApp.Visible = False
wordDoc = wordApp.Documents.Open(mAp
wordDoc.Bookmarks("memo_da
wordDoc.Bookmarks("custome
wordDoc.Bookmarks("custome
wordDoc.Bookmarks("address
wordDoc.Bookmarks("address
wordDoc.Bookmarks("city").
wordDoc.Bookmarks("state")
wordDoc.SaveAs(sFileName)
CType(wordDoc, Microsoft.Office.Interop.W
CreateWordDocument = True
Catch x As Exception
CreateWordDocument = False
MsgBox(x.Message)
Finally
NAR(wordDoc)
CType(wordApp, Microsoft.Office.Interop.W
NAR(wordApp)
GC.Collect()
End Try
End Function
Private Sub NAR(ByVal o As Object)
Try
System.Runtime.InteropServ
Catch x As Exception
MsgBox(x.Message)
Finally
o = Nothing
End Try
End Sub
Cheers!
ASKER
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?
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.
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.
ASKER
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
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
ASKER
I cannot Import 'Interop' -- it's not one of the options available to me
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
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.W ord.Applic ation
Dim wordDoc As Word.Document
Try
mAppPath = System.Reflection.Assembly .GetExecut ingAssembl y.Location
mAppPath = Microsoft.VisualBasic.Left (mAppPath, mAppPath.LastIndexOf("\")) & "\"
wordApp.Visible = False
wordDoc = wordApp.Documents.Open("C: \Documents and Settings\My Documents\VB\LetterheadWit hBMs.dot")
wordDoc.Bookmarks("TESTDAT A").Range. Text = Now.ToShortDateString
wordDoc.Bookmarks("TESTDAT A2").Range .Text = ("Yes, it worked.")
The two bottom lines are underlined in blue at "wordDoc.Bookmarks". Why is this happening?
:-(
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.W
Dim wordDoc As Word.Document
Try
mAppPath = System.Reflection.Assembly
mAppPath = Microsoft.VisualBasic.Left
wordApp.Visible = False
wordDoc = wordApp.Documents.Open("C:
wordDoc.Bookmarks("TESTDAT
wordDoc.Bookmarks("TESTDAT
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?
ASKER
Interface 'Word.Bookmarks' cannot be indexed because it has no default property.
Try this:
Dim oRng As Word.Range
oRng = oDoc.Bookmarks.Item("TESTD ATA").Rang e
oRng.InsertAfter(Now.ToSho rtDateStri ng)
Dim oRng As Word.Range
oRng = oDoc.Bookmarks.Item("TESTD
oRng.InsertAfter(Now.ToSho
ASKER
Cool!!
But how do I replace the bookmarked text with the text from the application?
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.ToShortDateS tring)
oRng.Text(Now.ToShortDateS
ASKER
Ah right, fair point! :D
Many thanks.
Many thanks.
ASKER
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.
Eg, if I have a letter containing say "<<NAME>>" and I want to replace <<NAME>> with "David" for example.
SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
That's good enough for me.
Cheers!
Cheers!
ASKER
Yes, I just tried
oRng.Text(Now.ToShortDateS tring)
and it didn't work.
oRng.Text(Now.ToShortDateS
and it didn't work.
ASKER
Ignore me -- my mistake - it's working now.
Cheers
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.
ASKER
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("TESTDAT A2").Range .Text = ("Yes, it worked.")
Any text inside of the bookmark gets replaced if you specify the Range.Text
wordDoc.Bookmarks("TESTDAT
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?
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.
ASKER
Thanks guys for all your help. I hope you're OK with the points split.
Cheers :D
Cheers :D
No problem!
No problem here either :)
MailMerge: http://support.microsoft.com/default.aspx?scid=kb;en-us;301656
BookMark: http://support.microsoft.com/default.aspx?scid=kb;en-us;316383