Hi to all. I need your help to do something that it's a bit complicated for me.
Some days before in this forum with the precious help of pbaldy I managed to use the code below which is very useful to send a different email to all recipients in a table. Now I was asked if it is possible to change the code so it can look through 7 different tables with dif structure but with common value the "BranchID", selects all branches with the same ID, exports their data into an xls file within a separate sheet for each table and then send the email. I hope I make it clear and I hope you can help me on this also. Thanks !!
Here is the code I use:
https://www.accessforums.net/reports...html#post48778
Dim qdf As DAO.QueryDef
Dim dbs As DAO.Database
Dim rstMgr As DAO.Recordset
Dim strSQL As String, strTemp As String, strMgr As String
Dim objOutlook As Outlook.Application
Dim objOutlookMsg As Outlook.MailItem
Dim objOutlookRecip As Outlook.Recipient
Dim objOutlookAttach As Outlook.Attachment
Dim DisplayMsg As Boolean
Dim varTo As Variant
Dim stWhere As String
On Error GoTo Err_SendMessage
Const strQName As String = "zExportQuery"
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs("q_temp")
strSQL = "SELECT DISTINCT ManagerID, ManagerEmail FROM EmployeesTable;"
Set rstMgr = dbs.OpenRecordset(strSQL, dbOpenDynaset, dbReadOnly)
Do While rstMgr.EOF = False
strMgr = DLookup("ManagerID", "ManagersTable", _
"ManagerID = " & rstMgr!ManagerID.Value)
strSQL = "SELECT * FROM EmployeesTable WHERE " & _
"ManagerID = " & rstMgr!ManagerID.Value & ";"
qdf.SQL = strSQL
qdf.Close
' Replace C:\FolderName\ with actual path
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
"q_temp", "C:\AccessAp\" & strMgr & Format(Now(), _
"ddMMMyyy_hhnn") & ".xls"
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(olMailItem)
With objOutlookMsg
' Set the Subject, Body, and Importance of the message.
.Subject = "Subject"
.Body = "Message"
.To = rstMgr!ManagerEmail
'.Importance = olImportanceHigh 'High importance
Set objOutlookAttach = .Attachments.Add("C:\AccessAp\" & strMgr & Format(Now(), _
"ddMMMyyy_hhnn") & ".xls")
' Resolve each Recipient's name.
For Each objOutlookRecip In .Recipients
objOutlookRecip.Resolve
Next
.Display
End With
rstMgr.MoveNext
Loop
Exit_SendMessage:
Set qdf = Nothing
Set objOutlook = Nothing
rstMgr.Close
Set rstMgr = Nothing
dbs.Close
Set dbs = Nothing
Exit Sub
Err_SendMessage:
MsgBox Error$
Resume Exit_SendMessage