View Single Post
  #7   Report Post  
Posted to microsoft.public.word.mailmerge.fields
Peter Jamieson Peter Jamieson is offline
external usenet poster
 
Posts: 4,582
Default Using a VBA function in my Word Mail Merge document

I looked everywhere I
could think of


1. It used to be in the Help for Word VBA :-)

2. The following tiny example should give you enough info to get started
- it's in response to someone who wanted a record counter

a. create a VBA class module. Let's say it is called Class1.

Insert the following code:
'----------------
Public WithEvents app As Word.Application

Private Sub app_MailMergeBeforeRecordMerge(ByVal Doc As Document, _
Cancel As Boolean)
Doc.Application.StatusBar = _
"Merging record " & _
Doc.MailMerge.DataSource.ActiveRecord

End Sub
'----------------

b. In an ordinary module (i.e. not a Class Module), put the following code

'----------------
Dim x As Class1

Sub ShowMergeRecordCounter()
Set x = New Class1
Set x.app = Word.Application
End Sub

Sub UnShowMergeRecordCounter()
Set x = Nothing
End Sub
'----------------

c. run ShowMergeRecordCounter to switch on application-level event
handling.
d. do your merge. Notice that the status bar display is constantly
replaced by the "standard" display
e. run UnShowMergeRecordCounter to switch off application-level event
handling.


And will the event code I write fire automatically, or
will the users have to hit a button or keys that essentially fire a

macro?

3. At some point you will have to do what ShowMergeRecordCounter does.
So you have either to run that kind of code in Auto macro or other
"new/open document event code", or you have to usurp an existing
command, or you have to get the user to click something. And notice that
these are /application/ events, so if the user happens to set off two
merges, the events will fire for both of them.

4. Finally, AFAIK one of the events (MailMergeBeforeMerge) does not fire
unless the user initiated the merge via the Mail Merge Wizard in Word
2002/2003. I can't remember what the position is in Word 2007. So you
would typically have to use class initialisation code to do any
necessary initialisation instead.


Peter Jamieson

http://tips.pjmsn.me.uk

On 14/01/2010 23:48, Bruce wrote:
Excellent Peter - much appreciated. Having come from quite some programming
of MSAccess, MSWord is pathetic. Just a few more questions (following your
comment "I'd go with macropod's suggestion") - how do I use the MailMerge
event? Do I set up a Sub MailMerge_Execute, or ...? I looked everywhere I
could think of (obviously not enough) and could not find anything on
MailMerge events. And will the event code I write fire automatically, or
will the users have to hit a button or keys that essentially fire a macro?

url:http://www.ureader.com/msg/10107949.aspx