Sub DoMerge()
Dim strMergeDoc As String
Dim objWordApp As Word.Application
Dim ObjWordDoc As Word.Document
Dim strResultDoc As String
Dim strResultPath As String
Dim r As Integer
Dim dbs As DAO.Database
Dim rs As DAO.Recordset
Dim strSubSQL As String
Dim tbl As Word.Table
Dim rw As Word.Row
Dim f As Integer
Set dbs = CurrentDb
strMergeDoc = "C:\Documents and Settings\Graham Skan\My Documents\MMsubMain.doc"
'Do Until .EOF
'strSourceSQL = "SELECT vwContractInfo.* FROM vwContractInfo WHERE bmID=" & lngBidID
Set objWordApp = Word.Application
objWordApp.Visible = True
Set ObjWordDoc = objWordApp.Documents.Open(strMergeDoc)
With ObjWordDoc.MailMerge
For r = 1 To .DataSource.RecordCount
'.OpenDataSource Name:="", Connection:=strConnection, SQLStatement:=strSourceSQL
.Destination = wdSendToNewDocument
.DataSource.FirstRecord = r
.DataSource.LastRecord = r
.Execute
'sub processing
.DataSource.ActiveRecord = r
If InStr(.DataSource.DataFields("Main1"), "ZZZ") > 0 Then
'create a recordset of subsiduary items belonging to the main record
strSubSQL = "SELECT tblSub.Sub1, tblSub.Sub2 " & _
"From tblSub " & _
"WHERE ((tblSub.[Main ID])=" & .DataSource.DataFields("Main_ID") & "); "
Set rs = dbs.OpenRecordset(strSubSQL, dbOpenDynaset)
Set tbl = ActiveDocument.Tables(1)
Do Until rs.EOF
Set rw = tbl.Rows.Add
For f = 0 To rs.Fields.Count - 1
rw.Cells(f + 1).Range.Text = rs.Fields(f).Value
Next f
rs.MoveNext
Loop
rs.Close
End If
'the new document created by MailMerge becomes the ActiveDocument. Save it and close.
'strResultDoc = strResultPath & !jobno & " Subcontract" & !ContractNumber & ".doc"
strResultDoc = "MMsubMainResult" & r & ".doc"
With objWordApp.ActiveDocument
.SaveAs strResultDoc
.Close wdDoNotSaveChanges
End With
Next r
End With
'Close the MailMerge main document
ObjWordDoc.Close wdDoNotSaveChanges
Set ObjWordDoc = Nothing
'.MoveNext
'Loop
End Sub
|