Sub Document_Open()
Dim strSrc As String, i As Long, strQuery As String
Dim XLAppObj As Object, XLWkBkObj As Object
strSrc = ActiveDocument.Path & "\Master Sheet.xlsm"
If Dir(StrSrc) = "" Then
MsgBox "Unable to locate the data source", vbExclamation
End If
Set XLAppObj = CreateObject("Excel.Application")
Set XLWkBkObj = XLAppObj.Workbooks.Open(StrSrc, , True, , , , , , , , , , False)
With XLWkBkObj
If IsNumeric(.Sheets("Appeal 1").Range("N5")) Then
strQuery = "SELECT * FROM `Appeal 1$` WHERE (`F14` < '75') And (`F1` IS NOT NULL)"
Else
strQuery = "SELECT * FROM `Appeal 1$` WHERE (`F13` < '75') And (`F1` IS NOT NULL)"
End If
.Close False
End With
XLAppObj.Quit
Set XLWkBkObj = Nothing: Set XLAppObj = Nothing
With ThisDocument
With .MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
Retry:
On Error GoTo ErrHandler
.OpenDataSource _
Name:=StrSrc, ReadOnly:=True, AddToRecentFiles:=False, LinkToSource:=False, _
Connection:="Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;" & _
"Data Source=StrSrc;Mode=Read;Extended Properties=""HDR=YES;IMEX=1"";", _
SQLStatement:=strQuery, SQLStatement1:="", SubType:=wdMergeSubTypeAccess
On Error GoTo 0
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
.MainDocumentType = wdNotAMergeDocument
End With
.Saved = True
Exit Sub
End With
ErrHandler:
'In case there's an error connecting to the data source, retry up to 5 times.
If Err.Number = 5922 Then
i = i + 1
If i < 5 Then
GoTo Retry
Else
MsgBox "Unable to open data source", vbExclamation
End If
End If
End Sub