Link to home
Start Free TrialLog in
Avatar of Richard
Richard

asked on

access-exporting to Word-Bookmarks or Custom Document Properties?

I am trying to export from Access to Word to make word documents.
I have seen in two books, two different ways of doing this.
The first is to export to a Word bookmark and the second is to set up Word Custom Document Properties.

I think that CDP sets up fields in the document.

I am wondering whether one is better than the other or whether they are pretty much the same. If one better then why?
Avatar of tbsgadi
tbsgadi
Flag of Israel image

If you're talking about Mail Merge then have a look at the following:

http://www.functionx.com/mailmerge/access.htm

Gary
Avatar of GrahamSkan
Bookmarks are designed to do that sort of job, but they do have a couple of problems. They can be accidentally deleted when editing. Also it is possible to set the text of a bookmark, so that the text follows the bookmark instead of being contained by it, which makes it hard to find later. If you don't need to programatically rework on the documents after creation, then neither of these will matter.

However one alternative is to use DocProperty  fields, and to set the values of the custom properties. My thought is that the properties could be modified later, perhaps inadvertently, so the document text will change when the fields get updated. These two events could be well apart, thus creating a mystery for the unsuspecting reader.

If you did want to go down the field route, I would suggest DocVariable fields. These can only be modifed programatically.
Doc properties are the best, in my opinion, because the information is stored in the document (as opposed to mail merge), so you don't need to have the data source open.  In contrast to bookmarks, you have the advantage of being able to use the same doc property value as many times as you need in the document, using DocProperty fields (for example, an address block in a letter and envelope).  Here is some typical code for creating a Word document and filling doc properties with values from Access.  You may also be interested in my latest ebook from Office Watch, Working with Word.
Private Sub cmdCreateWordDoc_Click()
'Created by Helen Feddema 15-Feb-2010
'Last modified by Helen Feddema 15-Feb-2010

On Error GoTo ErrorHandler

   Dim strDocHeader As String
   Dim appWord As Word.Application
   Dim strDefaultTemplatesPath As String
   Dim strTemplate As String
   Dim doc As Word.Document
   Dim docs As Word.Documents
   Dim strWordTemplate As String
   Dim strDocsPath As String
   Dim strTemplatePath As String
   Dim prps As Object
   Dim strShortDate As String
   Dim strLongDate As String
   Dim strTest As String
   Dim strAddress As String
   Dim strCountry As String
   Dim strSaveName As String
   Dim strTestFile As String
   Dim intSaveNameFail As Boolean
   Dim i As Integer
   Dim strSaveNamePath As String
   
   'Check for required address information
   strTest = Nz(Me![StreetAddress])
   If strTest = "" Then
      MsgBox "Can't send letter -- no street address!"
      GoTo ErrorHandlerExit
   End If
   
   strTest = Nz(Me![City])
   If strTest = "" Then
      MsgBox "Can't send letter -- no city!"
      GoTo ErrorHandlerExit
   End If
   
   strTest = Nz(Me![PostalCode])
   If strTest = "" Then
      MsgBox "Can't send letter -- no postal code!"
      GoTo ErrorHandlerExit
   End If
   
   strAddress = Nz(Me![StreetAddress]) & vbCrLf & _
      Nz(Me![City]) & ", " & Nz(Me![StateOrProvince]) & _
      "  " & Nz(Me![PostalCode])
   strCountry = Nz(Me![Country])
   If strCountry <> "USA" Then
      strAddress = strAddress & vbCrLf & strCountry
   End If
      
   Set appWord = GetObject(, "Word.Application")
   
   strLongDate = Format(Date, "mmmm d, yyyy")
   strShortDate = Format(Date, "m-d-yyyy")
   strSaveName = "Letter to " & Me![FirstName] & " " & Me![LastName]
   strSaveName = strSaveName & " on " & strShortDate & ".doc"
   strDocsPath = GetProperty("DocumentsPath", "")
   strWordTemplate = GetProperty("WordTemplate", "")
   
   'Check for existence of previously saved letter in documents folder,
   'and append an incremented number to save name if found
   i = 2
   intSaveNameFail = True
   Do While intSaveNameFail
      strSaveNamePath = strDocsPath & strSaveName
      Debug.Print "Proposed save name and path: " _
         & vbCrLf & strSaveNamePath
      strTestFile = Nz(Dir(strSaveNamePath))
      Debug.Print "Test file: " & strTestFile
      If strTestFile = strSaveName Then
         Debug.Print "Save name already used: " & strSaveName
         
         'Create new save name with incremented number
         intSaveNameFail = True
         strSaveName = "Letter " & CStr(i) & " to " & _
            Me![FirstName] & " " & Me![LastName]
         strSaveName = strSaveName & " on " & strShortDate & ".doc"
         strSaveNamePath = strDocsPath & strSaveName
         Debug.Print "New save name and path: " _
            & vbCrLf & strSaveNamePath
         i = i + 1
      Else
         Debug.Print "Save name not used: " & strSaveName
         intSaveNameFail = False
      End If
   Loop
   
   strDocHeader = "Test Document Header"
   
   Set docs = appWord.Documents
   Set doc = docs.Add(strWordTemplate)
   
   Set prps = doc.CustomDocumentProperties
   prps.Item("TodayDate").Value = strLongDate
   prps.Item("DocHeader").Value = strDocHeader
   prps.Item("Name").Value = Nz(Me![FirstName] & " " & Me![txtLastName])
   prps.Item("Address").Value = strAddress
   prps.Item("Salutation").Value = Nz(Me![Salutation])
   prps.Item("CompanyName").Value = Nz(Me![CompanyName])
   prps.Item("JobTitle").Value = Nz(Me![JobTitle])
   
   With appWord
      .Visible = True
      .Selection.WholeStory
      .Selection.Fields.Update
      Debug.Print "Going to save as " & strSaveName
      .ActiveDocument.SaveAs strSaveName
      .Activate
      .Selection.EndKey Unit:=wdStory
   End With
   
ErrorHandlerExit:
   Exit Sub

ErrorHandler:
   MsgBox "Error No: " & Err.Number _
      & " in " & Me.ActiveControl.Name & " procedure; " _
      & "Description: " & Err.Description
   Resume ErrorHandlerExit

End Sub

Open in new window

Here is a quote from Working with Word comparing the four methods to merge data from Access to Word:

Bookmarks
Advantages
You don't have to open the template's properties sheet; bookmarks are inserted directly into the template.
Bookmarks are more familiar to Word users than document properties.
A separate document is created for each record, which allows easy customization of specific documents.
There is no link to the Access database, so documents can be opened even on another computer.
Disadvantages
You can’t insert the same bookmark twice in a template; to display the same information in two or more places, you either need to create another bookmark or use a cross-reference field that references the first bookmark.
Users may inadvertently type into the text inside a bookmark, overwriting the exported value.
Document Properties
Advantages
Data from a document property can be displayed in multiple locations, using multiple DocProperty fields to display the same doc property value (for example, in a letter and a matching envelope).
A separate document is created for each record, which allows easy customization of specific records.
There is no link to the Access database, so documents can be opened even on another computer.
Disadvantages
You must create the needed document properties in the template, using the properties sheet.
TypeText
Advantages
No advance preparation of any kind is needed; this method works with a document created from the default Word template, or a default labels document.
There is no link to the Access database, so documents can be opened even on another computer.
Disadvantages
This method is suitable only for very simple documents, such as mailing labels or tabular lists.
Mail Merge
Advantages
This is the only method suitable for merging very large numbers of records, so many that it is impractical to create an individual document for each record.
Disadvantages
Customization of individual records is difficult, because all the data is merged to a single (possibly very large) document.
Creating a mail merge labels document is more complex than creating a labels document for use with the TypeText method.
With a live Mail Merge link, you can only open the merge document on a computer with access to the linked database, and this is a real memory hog.
Graham:  Maybe I need to add a 5th method, using DocVariable fields.  I will see if I can work up some code for this method.  There are certainly advantages (in some situations) to having tamper-proof ways of storing data in a document.
Avatar of Richard
Richard

ASKER

Is the DocVariable inserted as a field in the Word doc, but with programming behind the scenes in the VBA code?

Dim as String? (sorry rookie at work here)

Some pointers would be amazing.

Thanks Graham and Helen for the learned content
You can insert a field using code, but you have to tell the programme where to place it, so you are no better off.

You can create document variables or custom properties programatically . They do not themselves appear on the document (which is why we need fields), so we only need to set the name and value. However it is easier to insert the relevant fields if the property or variable already exists.

Just a note on Mail Merge. If you merge to a result document, that document's text is fixed and has no merge fields in it.

The main disadvantage is that there is facility in the merge itself for data from a one-to-many join, such as you would use a sub-form for in Access. There are ways round that, with fields or VBA code, but they aren't easy.
Here is some code to create a document variable.
Sub CreatVar(doc As Word.Document, strName As String, strValue As String)
Dim docvar As Word.Variable


strName = "MyVariable"
strValue = "some text"
For Each docvar In doc.Variables
    If docvar.Name = strName Then
        docvar.Value = strValue 'variable already exists so just set the value
        Exit Sub
    End If
Next docvar
'create variable and set its value
Set docvar = doc.Variables.Add(strName, strValue)

End Sub

Open in new window

For a merge (using doc properties and TypeText) that handles exporting from Access tables linked one-to-many, see my Access Archon #44 (attached).  The data from the "one" table is written to doc properties, and the data from the "many" table is written to a Word table, using TypeText.
accarch44.zip
The table expands as needed so it can accommodate any number of "many" records.
Here's a complete Access to word merge app.  This takes an Access data source and then pokes it into a Word Doc based on bookmarks.
Everything is controlled from the Access side.
JimD.

mmA2002.zip
Avatar of Richard

ASKER

Thanks GrahamScan

I am a little confused as to were this code 'goes'

ASKER CERTIFIED SOLUTION
Avatar of GrahamSkan
GrahamSkan
Flag of United Kingdom of Great Britain and Northern Ireland 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
Avatar of Richard

ASKER

I am sure that GrahamSkan has put me on the right lines, but I am a little confused as to how to put it into action.
I will continue privately with this and ask further questions as necessary.

As to answering the question he has fully answered my question as to which would be the best option. I just need to dig a bit deeper to operate it successfully.