Private Sub cmdWord_Click()
On Error GoTo ErrHandler
'Decalre Variables
Dim objWord As Word.Application
Dim cdrs As Recordset
Dim cdrsSQL As String
Dim strTable As String
Dim docsavelocation As String
'Set Values of Variables
cdrsSQL = "SELECT [Task Name], [Date Initially Due], [Action Required], [Due On], [ContactId] FROM ContactTasks where [ContactId]= " & Me.ContactId & ";"
Set cdrs = CurrentDb.OpenRecordset(cdrsSQL)
'copy the data to be converted to a word table
cdrs.MoveFirst
Do Until cdrs.EOF
strTable = strTable & cdrs![Task Name] & vbTab
strTable = strTable & cdrs![Date Initially Due] & vbTab
strTable = strTable & cdrs![Action Required] & vbTab
strTable = strTable & cdrs![Due On] & vbCr
cdrs.MoveNext
Loop
cdrs.Close
'copy all single entries to word document
Set objWord = CreateObject("Word.Application")
objWord.Visible = False
objWord.Documents.Add (strTemplateLocation) ' set from list box of available templates
If objWord.ActiveDocument.Bookmarks.Exists("ContactId") Then
objWord.ActiveDocument.Bookmarks("ContactId").Select
objWord.Selection.Text = Me.ContactId
End If
If objWord.ActiveDocument.Bookmarks.Exists("StudentId") Then
objWord.ActiveDocument.Bookmarks("StudentId").Select
objWord.Selection.Text = Me.StudentId
End If
'etc etc for as many bookmarks as you need to make available for template creation
'Insert Contact Details and create word table (NB Contact Details are from a 1:N Relationship)
If objWord.ActiveDocument.Bookmarks.Exists("ContactDetails") Then
objWord.ActiveDocument.Bookmarks("ContactDetails").Select
objWord.Selection.Text = strTable
objWord.Selection.ConvertToTable (vbTab)
'objTable = objWord.Selection
End If
objWord.Visible = True
docsavelocation = CurrentProject.Path & "\Sent Letters\" & Me.ContactId & ".DOC"
objWord.ActiveDocument.SaveAs (docsavelocation)
Set objWord = Nothing
ErrHandler:
Set objWord = Nothing
End Sub