Mail Merge: Part I

Office 2000

11 out of 22 rated this helpful

This article may contain URLs that were valid when originally published, but now link to sites or pages that no longer exist. To maintain the flow of the article, we've left these URLs in the text, but disabled the links.

Bon Mot

Introduction and Data Integration
By Cindy Meister A word processor becomes a truly powerful office tool once information and data from other sources can be integrated into its documents. The result can range from simple form letters to complex business reports. In this and subsequent articles, I'll look at various ways data can be brought into Word, starting with the built-in mail merge facility.

Mail Merge from the Developer Viewpoint
As a developer, you'll be interested in mail merge primarily from the viewpoint of automating the process of passing data into Word. If you aren't a Word user, you may not be familiar with the concept, so I'll mention a few basics as I go along. Word's mail merge can produce four basic kinds of documents: form letters, envelopes, labels, and catalogs. The first two are basically the same. Merge fields that link in data fields from the data source are placed in the document, and a section with the text and merged data is produced for each record in the data source. Envelope and form-letter merges differ primarily in that a setup dialog box will be presented for the envelope to allow the user to select envelope size, orientation, etc. A label mail merge also displays a set of dialog boxes before generating a page with a table on it, the cells of which correspond to the number and size of the selected label type. With the exception of the first cell, a Next field precedes the merge fields in each cell, so the data from more than one record is entered on the same page. The main difference between a catalog merge type and a form letter is that no section break is inserted between the data records - each follows directly after the other on the same page until the page breaks automatically once it's full. This is the merge type to use when the required result is a list, such as an address book or telephone directory.

1 of 16

3/21/2013 8:52 AM

Except for some changes in the dialog boxes and the ability to access "Views" for ODBC data sources (Word 95). and HTML format as data sources. in many respects. Word can also link to spreadsheet and text data sources using its internal converters (see FIGURE 1). the data source must be linked in. the mail merge feature in Word hasn't changed substantially in the last 10 years. As far as Word mail merge is concerned. DAO. before executing further mail merge commands: Set docMerge = ActiveDocument. there is wdNotAMergeDocument (corresponds to "Restore to normal Word document" in the Mail Merge Helper).for the user. otherwise it's ODBC if the drivers are installed. wdFormLetter. you can set the MainDocumentType property of the document's MailMerge object. you'll set up the Main merge document as a template so your program can re-use it (via Documents. What ought to be a fairly straightforward process is unfortunately fraught with pitfalls . As a matter of fact. and wdMailingLabels. This property is useful for unlinking a data source and determining the state of a document.aspx Mostly. Besides the constants wdCatalog. the capabilities have degenerated since Microsoft put most of the development resources into "Web" options in the last two versions. RDO. For the occasion where you need to automate the creation of the Main merge and for the developer.Add) every time a particular document must be produced. FIGURE 1: Activating the Select method in the Open Data Source dialog box enables the user to select from all available connection and ADO don't exist. giving little attention to data integration.Mail Merge: Part I http://msdn. The default data source Connect method for other Office applications (Excel and Access) is DDE. MAPI Address Books (Word 95). 2 of 16 3/21/2013 8:52 AM .MailMerge With docMerge If .MainDocumentType = wdFormLetters End If End With Getting the Data Besides setting up a document as one of the four types of Main merge documents. The most basic Word data source is a Word table in a Word document.MainDocumentType = wdNotAMergeDocument Then . wdEnvelope.10).

dqy (MSQuery).db/. unlike with many other data source types. To save you some frustration and time. not for record delimiters. there are a couple of work-arounds: 1) Create the Header file as a Word table.dbf (Paradox. No problems with things like mismatched quotes or special characters and symbols occur. mail merge recognizes data sources of these file types: .htm. But if you're merging in Office 97 (and on Office 2000 machines upgraded from an earlier version). you're likely to run into a number of problems: The individual fields aren't recognized. This is fine. the names all run together as a single field.mdb/.): FirstName~LastName~Address~City~PostalCode 3 of 16 3/21/2013 8:52 AM . . too.dat). Besides Word tables. be it a Windows. so that Word automatically uses its internal text file converter. including graphical objects (but not formatting).mde (Access). . DOS. 3) rename the file with an extension the ODBC driver doesn't recognize (such as . The culprit is the text ODBC driver with which Word does not communicate correctly. or 2) duplicate the first line of the Header file. so that it contains two lines with the same number of fields using the same field delimiter (Note: This only works for field delimiters.qry/.rtf. an annoying automation obstacle you'll encounter in all versions of Word is a dialog box requesting you to confirm the field and record delimiters. For this. FoxPro. "Virgin" Office 2000 installations shouldn't have this problem. or mainframe application. you have three options: 1) uninstall the ODBC driver. If you use a Header file to define the field names for the data source (as is often the case with data coming from a mainframe). To link up to your data source. and . and error messages like "Word was unable to open the data source" appear. but the purpose of most automation is to use data from sources outside Word. . as Microsoft didn't include the Text ODBC converter as one of the recognized link methods. 2) activate the Select method checkbox so you can specify Word's internal text file converter as the link method (see FIGURE 1). using text files as a data source was a fairly straightforward proposition. dBASE). Text Files Delimited text and comma-separated value files are standard data formats. .10). here are some tips to get around the more frequently encountered problems with various non-Word data sources.Mail Merge: Part I http://msdn. Almost any program that imports and exports data supports one or The mail merge will pretty much transfer the fields' content as-is. Up through Word 95.xls (Excel). .csv/.microsoft.

only a DDE connection will do. You have to rely on SendKeys to make the proper selection. even if you use one of the built-in constants. However. Excel is very reliable as a data source." as illustrated in FIGURE 2. you need to use Word's internal spreadsheet converter. and save it as a Word document for use as the data source. you'll be a bit nonplussed to see that all the records are included.Mail Merge: Part I http://msdn..SaveAs Left(szFileName. if the version of Word is pre-2000. which allows you to specify any range. Unfortunately. Bfle. and you want to merge to data not on the first spreadsheet in the workbook.using MSQuery. What does work is opening the document manually in Word. For a DOS file.Co SendKeys "^{HOME}MS-DOS Text{ENTER}" Set doc = Documents. Again. making it easy to sort and filter lists. three types of link methods are available for the merge: DDE. On a typical installation. When you first set up the link. Excel has powerful data-management features. with ASCII Code Page encoding. To merge to a filtered subset of records. You can import and link to data from many other sources . select the correct conversion filter.3) & "do Excel Workbooks All things considered. it's generally ignored by Word. and create charts and pivot tables. Word provides no way to specify the correct converter. Suppress them by setting a Query Option in Word to show all records where a particular field that you know always has an entry (an ID .aspx FirstName~LastName~Address~City~PostalCode Text files created with non-ANSI character sets present a problem.. instead of: Vous êtes allés á Bâle. For example. Looking at the OpenDataSource method of the MailMerge object. The best one to use depends very much on what aspect of the data is important. in the Open method. (Record the action in a Word macro if you need to get the VBA code for automation purposes. and confirm it in the Confirm Conversions dialog box: szFileName = "E:\My Documents\Mergdata. analyze the data.10). there is no ideal way to automate this. for instance) to "is not blank.txt" Options.Open(FileName:=szFileName) doc. Word will open them for mail merge automatically. you may notice the Format argument and think this provides a way without recognizing their origin or giving you the opportunity to convert them.) 4 of 16 3/21/2013 8:52 AM . With Tools | Options | General | Confirm conversion at open activated. but that those filtered out in Excel show no data. and Word's internal spreadsheet converter.even ones Word doesn't support . ODBC. Len(szFileName) . you could get something like this: Vous ^tes all.

rather than trying to reformat an existing column of data. ODBC is certainly the fastest. a NULL value (empty result) is passed to Word for that record's field. a user may contact the Help Desk in panic because the mail merge data coming from Excel is mixed up. This behavior is documented in Knowledge Base article Q141284 (http://support.9 1. Of all the link methods.10). Use this technique. If the data in a field doesn't match (there's text in a numeric field.##0.00" } Formatted result 03-Jan-1999 Original field { MERGEFIELD SaleDate} { MERGEFIELD SalesAmt} 1245. because another problem with ODBC occurs if the Excel column mixes data types. or the merge stops after a certain number of type the formula =Text(C2. records are repeating.aspx FIGURE 2: Recognize and suppress filtered record from an Excel data source. it will also not pass through date and number formatting. The ODBC driver scans the first eight rows of the Excel data source in order to determine a field's data type.asp). Occasionally. This is because ODBC only passes across the underlying data.245.Mail Merge: Part I http://msdn. "dd-mmm-yyy"). assuming it's in cell C2. As an alternative. You can remedy this problem in your Main merge document by adding number and data format switches to the merge fields affected. (Remember. But besides older ODBC drivers not allowing you to select a range in the then copy it for all the records.90 FIGURE 3: Use formatting switches to change how dates and numbers are presented in the mail merge for example). you can create an additional column in the Excel spreadsheet that converts the numerical data to text using the Text function. The usual reason for this is 5 of 16 3/21/2013 8:52 AM . Note the uppercase "M" for month and the use of double quotes. For use [Alt][F9] to toggle between field result and field code display. to pass across the date in FIGURE 3 as literal text.) Original result 3/1/1999 0:00:00 Field and formatting switch { MERGEFIELD SaleDate \@ "dd-MMM-yyyy" } { MERGEFIELD SalesAmt \# "#. as shown in FIGURE 3.

and date formats apply here to DDE vs. and every time the mail merge needs to re-contact the data source (when querying. the corresponding approach for passing Word the desired number of formats as literal strings via ODBC is to use the Format function in expressions in the query providing the data (see FIGURE 4). because the company will turn to the person who provided them with the application! If this happens to you. the longer the SQL behind it.10). If you're familiar with Access. you must use DDE.aspx that the Main merge document has become damaged. However. either go back to your original. Access As mentioned earlier. However. so an ODBC merge displays the information the way you want to see it. it might come up in the Access window instead. and the greater the chance that Word will reject it as a data source with the The problem can usually be solved by removing any customized Application Title on the Startup dialog box. for example). backed up copy of the Main merge document. note that you can't guarantee that the parameter dialog box will be displayed in the Word environment. you can imagine that most typical installations will be dangerously low on resources by the time three or more copies of Access are open. More reliable is to request the user information in the Word environment. ODBC was definitely the way to avoid this problem. In Access. another instance is loaded. DDE is the default link method for Access. as well as to speed things up. The more complex the query. or copy everything from the damaged Main merge document to a new document except for the last paragraph mark. If the data source is a parameter query. The same observations concerning speed. go through Tools | Mail Merge to set the main document type and link in the data source. If your code doesn't set up the mail merge. which is an issue for the developer. If it can't find it.Mail Merge: Part I http://msdn. Until Office 2000. There is an issue with DDE in Office 97 and 2000: The built-in procedure that sets up the DDE link requires the default title bar caption. uninformative message "Word cannot open the 6 of 16 3/21/2013 8:52 AM .com/en-us/library/aa140183(v=office. another instance of Access is run. ODBC as for Excel. then pass it as part of a SQLStatement argument in the OpenDataSource method. FIGURE 4: Convert numerical data to literal strings (done here using the Format function). which is accessible from Tools | Startup. whatever changes were made in the ODBC drivers that were not accounted for by the Word 2000 developers make this an uncertain option. number.

or File DSNs for installed ODBC drivers are available. you have an alternative. you also need to download Wdvfpdsn. System. or other data file type (such as delimited text or an Excel spreadsheet) for use as the merge data source. Unfortunately. VBA: To Link or Not to Link Now that you've decided which Main merge document type you need. at least doubles the capacity MSQuery is allowed. You can get around this limitation using the Connect. This code snippet links to the Customers table in NorthwindCS. and SQLStatement1 arguments of the OpenDataSource method. etc. Others Linking to other data sources is becoming more and more difficult with each succeeding version of MDAC. The SQLStatement and SQLStatement1 arguments each allow a maximum of 255 characters in the string. you'll see this problem. or you have to set up a DSN through the FoxPro VFP driver. even though you're able to view it in the Main merge document. SQLStatement.aspx data source. Possible work-arounds are to change the field types.).here it works fine) or Access (as a linked table). If you've installed MDAC 2. This can happen if the fields are of data type NCHAR/NVARCHAR (Unicode strings. when moving to the Office 97 Unicode interface.dbf files. What worked in Word 6 or Word 97 may well not function in a later version. which." There are some query types to which Word can't set up a link at all.PW SQLStatement:="SELECT * FROM Customers" When using SQL Server as a data source.asp).microsoft. you need the Borland Database Engine (BDE). thus seriously limiting the usefulness of MSQuery.UID=<your_user_name>. including being able to accept query strings longer than 255 characters. If the upsizing wizard has been used to convert an Access database to SQL Server. e. Word lost some Mail merge only recognizes the data sources listed in the Open Data Source dialog box. _ Connection:="DSN=SQL_UserDSN. even if User. Here you may well encounter another hurdle: To use the FoxPro driver with Word's mail merge.Mail Merge: Part I http://msdn. and 7 of 16 3/21/2013 8:52 AM .exe from the Microsoft Web site and run it (http://support. or to create a view that returns non-Unicode data. the field content may be lost during the merge process. Microsoft has provided a button to run MSQuery (an applet associated with Excel). to link to dBASE . while limited.sql.OpenDataSource Name:="".com/en-us/library/aa140183( /kb/articles/Q237/2/84. so there's no way for the user to directly access Oracle or Microsoft SQL Server information.10). In this case. aggregate ("group-by") queries.1. To work around this. for example. the only work-around is to first link the information into Excel (via MSQuery . For a user. your only recourse is to export the query result to an Access table.g. then set up the mail merge to that data source. As a developer. created as a DSN in the 32-bit ODBC manager: ActiveDocument.MailMerge.

x Write.xls". LinkToSource:= what data source and link method are appropriate.OpenDataSource Name:= _ "E:\My Documents\XLTestData. ActiveDocument." SQLStatement:="SELECT * FROM 'Data'".MailMerge. _ SQLStatement:="". ' Recorded macro. Connection:="Data".MailMerge. ' Recorded macro. The link must be broken before you save the file. _ ConfirmConversions:= False. however. that you can't specify certain types of link methods via VBA.MaxBufferSize=2048. the mail merge facility will automatically select the default DDE method if it's available. or as a Main merge document. Compare the procedures in FIGURE 5. SQLStatement End Sub Sub LinkXLDDE() ' Connect to an Excel data source using DDE.PageTimeout=5. LinkToSource:= True. Word hard-codes the complete path to the data source in the document's binary file format. SQLStatement1:="" End Sub Sub LinkXLConverter() ' Connect to an Excel data source using ' Word's spreadsheet converter.DBQ=E:\My Documents\XLTestData. you can see the non-encoded parts of the file. Converting a Main merge document back to a normal Word file doesn't affect any merge fields that have been inserted.10). however. and whether the link to the data source should be saved with it. 8 of 16 3/21/2013 8:52 AM .Mail Merge: Part I http://msdn. Internally. If it will change. it's time to turn your attention back to the Main merge document. you can't differentiate between DDE and Word's internal spreadsheet converter for an Excel worksheet. you should save the Main merge document without the data source. The next step is to decide whether the file should be saved as a regular Word (If you open a Main merge document in an editor. because Word and VBA don't provide a way for you to check and change the link before Word tries to resolve it when the document is opened. this isn't a problem. Be aware. _ ConfirmConversions:= False.OpenDataSource Name:= _ "E:\My Documents\XLTestData.MainDocumentType = _ wdNotAMergeDocument The most reliable way to get the proper syntax for the OpenDataSource method is to record the linking process as a macro. Sub LinkXLODBC() ' Connect to an Excel data source using ODBC.xls". but it will remove the data source and any query options: Activedocument. Connection:= _ "DSN=Excel Files.) As long as the data source doesn't move. and link it to VBA after opening the file. For instance. such as the old Windows 3._ Format:=wdOpenFormatAuto. ActiveDocument. including the path to the data source.xl & "DriverId=790.MailMerge. _ Format:=wdOpenFormatAuto.

_ ConfirmConversions:= False. They don't always act as you'd expect... solves the problem neatly: Sub AutoOpen ' AutoOpen executes when a document is The Ask field stores it in a bookmark. \. or the information to be included is a one-time thing. Once Word is closed. ' Link up to the Outlook Contact List. Both display a prompt when updated. this means Schedule+. Then.aspx ' Recorded macro.. or for every record in the mail merge by including the \a switch (see FIGURE 6).. either because they have no direct access to the data source.olk" and will have to work through a couple of dialog boxes. which can be displayed or otherwise referenced during the merge using a Ref field. For mail merge. Because the prompts aren't shown in context with the text.UseAddressBook Type:="olk" End Sub Interacting with the User After opening the Main merge document and data source. But there are occasions where you'll want to interact with the users. 9 of 16 3/21/2013 8:52 AM . Word doesn't link to any Address Book directly. There are two fields that can be inserted into a document to get user input (and they don't require VBA): Fillin and Ask.. the user will see "Word Cannot Find Its Data Source C:\. the following procedure.MailMerge. ActiveDocument. Connection:="".FileConverters("MSBiff")._virtual_file_.. _ OpenFormat.. it's useful to nest merge fields displaying relevant data in the prompt text. Make sure the document or template is saved without the data source. this virtual file is destroyed. The prompts can be displayed once for the entire mail merge. you may be all set to produce the mail merge result. or an Outlook Contacts list. One type of data source you'll always want to attach using VBA when the Main merge document is opened is an Address Book.xls".OpenDataSource Name:= _ "E:\My Documents\MergData. SQLStatement:="". this links using DDE! ActiveDocument. Word can work with data from any MAPI-registered address book. an Exchange PAB.Mail Merge: Part I http://msdn. but converts its contents to a Word table in memory. So when a Main merge document with an Address Book data source is opened. For Microsoft products.MailMerge. but only the Fillin field displays the user input directly. _ Format:=Application. LinkToSource:= True. saved in the document or its template.10). _ SQLStatement1:="" End Sub FIGURE 5: Three recorded macros. When

microsoft.Mail Merge: Part I http://msdn. With ActiveDocument.10). if the data source contains a lot of records) to link to the data source directly via DAO/ODBC or ADO. Before looping through the data records. You can prevent this behavior by locking the fields until the mail merge is executed (see FIGURE 7).MailMerge. You also don't want to confuse the user by showing irrelevant prompt information from a former session with the Main merge document.Execute End With End Sub FIGURE 7: Managing Fillin and Ask fields in a user-friendly manner.aspx FIGURE 6: Prompt for user input using a Fillin or Ask field: result and field codes. This solution is based solely on Word VBA. e. or some standard text (e.g.Bookmarks("txtSalutation") _ . The UserForm_Initialize event handler calls the FillList function. (This topic will be covered in a future article. One feature Word doesn't have is a way to freely select records to merge that don't meet a common criterion.MailMerge.Range.) The SelectContacts procedure is the starting point. Sub AutoClose() ' Set Fillin field to "empty" and keep it ' from updating when not merging.Destination = wdSendToNewDocument .Bookmarks( _ "txtSalutation"). which fills the ListBox with data from a specified field in the data source.Fields(1) . calling the UserForm in FIGURE 8. however. . see Listing One. but it would also be possible (and faster.g.Text = "" . You can provide this for your users within the Word environment with a UserForm and a bit of code.Locked = False .com/en-us/library/aa140183(v=office. What's slightly annoying. the QueryString is adjusted to 10 of 16 3/21/2013 8:52 AM .Locked = True End With End Sub Sub RunMerge() With ActiveDocument ' Unlock Fillin field so it is updated ' during the merge process. when a new document is created from a template.Fields(1).Result. set the field's result to an empty string.Range. "Salutation appears here"). is that Word tends to display Fillin field prompts at times other than when a merge is executed.

The same UserForm is modified slightly to accommodate the additional functionality.aspx sort them by the same field being accessed for the list. Instead. it's simply hidden so all settings remain intact. so all records in the current selection are available to the search. GetUserSelection runs through the items in the list and picks out those that were selected. The array is then passed to the CreateQueryString function that puts together the "Word SQL" to specify the individual records.Mail Merge: Part I http://msdn. FIGURE 8: Enabling the user to select records from a list. These settings are made in the UserForm_Activate event handler. Listing Two extends the basic code. Instead. Because filling the list is time consuming. It then uses the FindRecord 11 of 16 3/21/2013 8:52 AM . but it's necessary to know what value should be typed into the Find What text box. When the user confirms the selection by clicking OK. the appropriate mode is determined from the UserForm's caption. Finally. The ListBox is set to MultiSelect so every entry the user clicks on will be Once OK is clicked. putting them into an array. With a bit of modification. FIGURE 8). the entire QueryString is concatenated and applied to the data source in the QueryTheData procedure. which is executed every time the form is displayed. Filling the list is slow due to the way Word scrolls through the records when VBA is used: It always restarts at record one for each next record call. you can present the user with a list from which to choose.10). The FindUserSelection procedure makes sure the first record is the active one. Note: the syntax may be different from what you're accustomed to: WHERE (("ContactName" = 'John Doe' )) OR (("ContactName" = 'Mary Brown')). you can use the same basic approach to allow users to search for a specific record. and counts forward. The form caption and the MultiSelect property of the ListBox need to change according to which command bar button is activated (top. the UserForm is no longer being unloaded when the dialog box is dismissed. The mail merge feature provides the Find Record dialog box (the "Binoculars" toolbar button). and finding records can be required fairly often (in contrast to just selecting records for the merge).

Destination to wdSendToNewDocument. but may not work reliably . Executing the Merge Many people think that once they can view the individual records in the Main merge document that the merge is complete. and there's no way to suppress it (unless you take a chance on SendKeys {Enter}). consult the Knowledge Base article Q155314: "How to Format the Fax Number Field When You Merge to Fax.or at all . For faxing and e-mail.rtf or HTML format). nor can the merge be executed. Clearly." It's available at http://support. From VBA.e. However. a catalog mail merge must be merged to a new document before it can be printed. For details. there's more to a mail merge. the fax number or e-mail address must be in one of the data source's merge fields. Word also lets you merge a specified range of records.10). Afterwards. rather than in the e-mail body.g. The mail merge can be sent directly to the printer. The functionality could be further extended by allowing the user to specify from which field the Select and Find lists should be filled. e. Instead. or list entry per record in the data source. you won't want to select this option. unless you send the resulting document as an attachment. Besides filtering records using query options (i.Mail Merge: Part I http://msdn. this feature has 12 of 16 3/21/2013 8:52 AM .aspx method to locate the user's choice. for example. then print the result. although normally this only makes sense for letters. Form letters. Word displays the Print dialog box. I leave this as an exercise to the reader. You're now acquainted with the types of mail merge documents available and the aspects of using various data sources. from record number 5 to envelopes. set the FirstRecord and LastRecord properties of the MailMergeDataSource object. set the MailMerge.asp. Hint: Word VBA has a MailMergeDataFields collection. the user can't flip through the records. If this isn't done (due to a bug in Word 97 and 2000). and labels can also be sent to a MAPI-compliant fax printer or the default e-mail program. label. By the way. This works fine in Word 2000. the same method is used to search for a record that isn't in the recordset. envelope. as well as with many of the VBA commands for the Word mail merge object model. Conclusion That covers the basics for automating Word's mail merge. The feature is actually meant to generate one letter. if you're automating the entire process. Fax numbers must be formatted so that mail merge recognizes them correctly. You can build on the code earlier versions. which is available for download (see end of article for details).com/en-us/library/aa140183( /kb/articles/Q155/3/ Although you can print single envelopes or letters this way. An e-mail letter can only be sent as plain text (no . with the QueryString property of the DataSource object).

I'll look at how to supplement the built-in mail merge feature.swissonline. ''' The basic SQL statement. so user can selec ' records. Private Const SQLSelect As String _ = "Select * from Customers" ''' The field from which the list is built. Option Explicit ' Constant values for list of data. formatted text inclusions. and managing conditional. based in Switzerland. one-to-many relationships. Five years experience as head of administration in an international organization and a Bachelor of Science provide her with a broad background for understanding customer requirements. It will be interesting to see what they do in the next version of Office.Caption = Trim(CStr(NrRecs)) & " Records" End Sub ' Code in project module.10).microsoft. have given her an in-depth knowledge of Office and Word. Begin Listing One . In Part II. and as Sysop in the CompuServe Word forum. You can reach her at mailto:cindymeister@swissonline. Private Const RecOrder As String = "Country" 13 of 16 3/21/2013 8:52 AM . with customers in four countries (and counting) and is a regular contributor to the German edition of Inside Word. Cindy Meister owns a consulting business. Private Const FldSelect As String = "ContactName" ''' The field on which the merge records are /cindymeister. Four years as a Microsoft MVP for Word support. For general questions on Word and links to other useful sites. we can only hope that Microsoft brings it up to the current standards of data integration technology. Cindy's fully bilingual (English and German). Before becoming independent. Option Explicit Private Sub cmdCancel_Click() Unload Me End Sub Private Sub cmdOK_Click() Dim aSelectList()As Variant Dim szQueryString As String aSelectList() = GetUserSelection(lstRecords) szQueryString = CreateQueryString(aSelectList()) QueryTheData szQueryString Unload Me End Sub Private Sub UserForm_Initialize() Dim NrRecs As Long NrRecs = FillList(lstRecords) lblNrRecs. The article will cover topics such as formatting. making it more versatile and powerful.aspx lots of potential for improvement. Merge: Part I http://msdn.Select contacts for mail merge 'Code behind UserForm. she spent three years as a consultant/trainer for Deloitte & Touche in visit her Web site at http://homepage.

DataSource With MMSource ' Sort according to the field.1 ' If item has been selected.ListCount Listcounter = 0 If NrItems = 0 Then ReDim aList(0) aList(0) = "None" GetUserSelection = aList() Exit Function Else ' Loop through all items in ListBox.ListBox) _ As Variant ' Get all user selections from multiselect list.QueryString = SQLSelect & " ORDER BY " & """" & _ FldSelect & """" ' Get the record count.Mail Merge: Part I http://msdn. Dim aList()As Variant Dim NrItems As Long Dim ItemCounter As Long Dim Listcounter As Long NrItems = lst. ReDim Preserve aList(Listcounter) aList(Listcounter) = lst. If lst. frmMailMerge.DataFields(FldSelect).MailMergeDataSource Dim NrRecs As Long Set MMSource = ActiveDocument.AddItem . .Selected(ItemCounter) = True Then ' Put value from list in array. ReDim aList(0) 14 of 16 3/21/2013 8:52 AM .ListBox) As Long ' Fill list with records from a field in the data so Dim MMSource As Word.MailMerge.List(ItemCounter) Listcounter = Listcounter + 1 End If Next ItemCounter End If If Listcounter = 0 Then ' If user has made no selection.ActiveRecord ' Go to the first record and get field entry.Value ' Repeat until all records have been read. .aspx Sub SelectContacts() ' Display Userform with list from data source.ActiveRecord = wdFirstRecord lst.ActiveRecord = wdLastRecord NrRecs = .com/en-us/library/aa140183( = wdNextRecord lst.Value Loop End With FillList = NrRecs End Function Function GetUserSelection(lst As MSForms.Show End Sub Function FillList(lst As MSForms.10). .ActiveRecord < NrRecs . Do While .AddItem .DataFields(FldSelect). For ItemCounter = 0 To NrItems .

Hide FindUserSelection Case Else Debug.Hide Case Is >= "Find" Me.QueryString = _ SQLSelect & " WHERE " & szQueryString & _ " ORDER BY " & RecOrder End Sub End Listing One Begin Listing Two .Caption. Dim TheString As String Dim Listcounter As Long ' Required syntax for MSWord: ' (("ContactName" = 'John Doe')) OR ' (("ContactName" = 'Mary Brown')) For Listcounter = LBound(aList())To UBound(aList()) If Len(TheString) <> 0 Then ' Include ORafter first item. TheString = TheString & " OR " End If TheString = TheString & "((" & """" & FldSelect & """" & " = '"& aList(Listcounter) & "' Next Listcounter CreateQueryString = TheString End Function Sub QueryTheData(szQueryString) ActiveDocument. Option Explicit Private Sub cmdCancel_Click() Me.aspx aList(0) = "None" End If GetUserSelection = aList() End Function Function CreateQueryString(aList()As Variant) As Stri ' Build query string to include all item ' in user selection array.10).Caption.Print Mid( 1) 15 of 16 3/21/2013 8:52 AM .Mail Merge: Part I http://msdn. 1) Case Is >= "Select" Dim aSelectList()As Variant Dim szQueryString As String aSelectList() = GetUserSelection(lstRecords) ' No user selection was made.DataSource. so nothing happens If aSelectList(0) = "None" Then Exit Sub szQueryString = CreateQueryString(aSelectList()) QueryTheData szQueryString Me.Find ' Code behind UserForm.MailMerge.Hide End Sub Private Sub cmdOK_Click() Select Case Mid(Me.

.10). lstRecords.FindRecord FindText:="x". 1) End Select End Sub Private Sub UserForm_Initialize() Dim NrRecs As Long NrRecs = FillList(lstRecords) lblNrRecs.Caption. lstRecords.MultiSelect = fmMultiSelectSingle Case Else Debug. 16 of 16 3/21/2013 8:52 AM . Field:="unknown" End With End Sub End Listing Two © 2013 Microsoft.MultiSelect = fmMultiSelectMulti Case Is >= "Find" ' Single selection only.Caption Select Case Mid(Me.ActiveRecord = wdFirstRecord ' Find the selected record.ActionControl. All rights Me.DataSource ' Go to first record so that all ' records are available in the search.Caption = CommandBars. . for find.FindRecord FindText:=frmMailMerge.Mail Merge: Part I http://msdn.lstRecords. .aspx End Select End Sub Private Sub UserForm_Activate() ' Reset control properties when form is = Trim(CStr(NrRecs)) End Sub & " Records" ' Code in project module that differs from Listing 2.Print Mid(Me. Sub FindUserSelection() ' Find record user selected With ActiveDocument. lstRecords.Text Field:="ContactName" ' MS BUG!!! ' Search a record not in the data ' so that merge operates properly. 1) Case Is >= "Select" ' Get rid of previous selection.MultiSelect = fmMultiSelectSingle ' Activate multiselect.MailMerge.Caption.

Sign up to vote on this title
UsefulNot useful