Link to home
Start Free TrialLog in
Avatar of shieldsco
shieldscoFlag for United States of America

asked on

Attach Excel Files to Outlook Emails from Access

I am trying to attach an external Excel files to emails from a folder using the following code.  The file name is in an Access table. For each email there is a related Excel file with the name of file equal to the tblTempShipNotice.Adjudicator. The email address is in the same table.


 
  Dim sMail                 As String
    Dim objOutlook            As Object
    Dim rs                    As DAO.Recordset
    Dim sSQL                  As String
    Dim strName               As String
    Dim sSubj                 As String
    Dim sBody                 As String
    Dim sTo                   As String
    Dim strCC                 As String
    Dim sCC                   As String

    'Get Email Addres
'    sSQL = "SELECT tblTempShipNotice.Email, tblTempShipNotice.Lname FROM tblTempShipNotice;"
    sSQL = "SELECT tblTempShipNotice.Email, tblTempShipNotice.Lname, Concatenate(""SELECT Emails FROM tblFO WHERE FO='"" & Nz([FO],""~999"") & ""';"","";"") AS CCEmails " & vbCrLf & _
           "FROM tblTempShipNotice;"

    Set rs = CurrentDb.OpenRecordset(sSQL, dbOpenSnapshot)
    With rs
        If .RecordCount <> 0 Then
            Set objOutlook = CreateObject("Outlook.Application")
            Do While Not .EOF
                'Initialize the variable for each loop
                strName = ""
                sMail = ""
                sSubj = ""
                'Populate the variables with our record data
                strName = Nz(rs![Lname], "")
                sMail = sMail & ";" & Nz(rs("Email"), "")
                strCC = Nz(rs![CCEmails], "")
                If strCC <> "" Then strCC = strCC & ";"
                Call Outlook_SendEmail(objOutlook, sMail, strCC, sCC, sSubj)

                .MoveNext
            Loop
            Set objOutlook = Nothing
        End If
    End With
End Sub

Function Outlook_SendEmail(ByVal objOutlook As Object, _
                           ByVal sMail As String, _
                           ByVal strCC As String, _
                           ByVal sCC As String, _
                           ByVal sSubj As String)
    Dim objEmailMessage       As Object

    Set objEmailMessage = objOutlook.CreateItem(0)
    With objEmailMessage
        .To = sMail
        If strCC & "" <> "" Then
            .cc = sCC
        End If
        .cc = strCC
        .Subject = sSubj
        .SentOnBehalfOfName = "OSOMHAHQSerialClaims@hhs.gov"
        'Set body format to HTML
        .BodyFormat = olFormatHTML
        .Subject = "Serial Claims Initiative - All Claims Approved for Payment by CMS in Appeal(s) Assigned to You - - [Serial Claims Spreadsheet #[Numbering -based on the number of CMS Identified Spreadsheet]"
        sBody = "As part of the Serial Claims Initiative (SCI), CMS has indicated its intent to pay all of the related claims in an appeal(s) currently assigned to you. The Medicare Appeals Contractor has identified existing claims for coverage of the same durable medical equipment, for the same beneficiary, in identical or near-identical circumstances. A notification from the Medicare Appeals Contractor has been included for your information. " & _
                "<br><br>Please find attached a template for a fully favorable stipulated decision which you may wish to use for this appeal.  Though all claims must be, and continue to be, adjudicated separately by OMHA, you may wish to utilize this template to promote consistency among decisions across the agency. <br><br>Thank you for your consideration and if you have questions, please do not hesitate to contact me. <br><br>" & sBody & "</table><br><b><i><br>Thank you,<br><br>LLLL R. Mel<br>Branch Chief, Special Initiatives Branch " & _
                "<br>Field Operations Division<br>Department Services<br>XXX Davis Highway, Suite 2001<br>Mrto, VA  22222<br>Phone: (999) 777-7799<br><br></i></div></body></html>"
        .HTMLBody = sBody
        .Display
    End With
    Set objEmailMessage = Nothing
End Function

Public Function GetCCadresses(ByVal mail As String) As String
    Dim sql As String
    sql = vbNullString
    sql = sql & "SELECT tblFO.Emails  AS cc" & vbCrLf
    sql = sql & "FROM tblFO INNER JOIN tblTempShipNotice" & vbCrLf
    sql = sql & "ON tblFO.FO = tblTempShipNotice.FO" & vbCrLf
    sql = sql & "WHERE tblTempShipNotice.Email = """ & mail & """;"

    Dim db As DAO.Database
    Set db = CurrentDb

    Dim rs As DAO.Recordset
    Set rs = db.OpenRecordset(sql, dbOpenSnapshot)

    Dim cc As String
    While Not rs.EOF
        cc = cc & rs("cc") & ";"    '// adjust to fit your needs
        rs.MoveNext
    Wend
    rs.Close
    GetCCadresses = cc
End Function

Open in new window

Avatar of Daniel Pineault
Daniel Pineault

Inspire yourself of the function found at http://www.devhut.net/2010/09/03/vba-send-html-emails-using-outlook-automation/ to include attachments in your outlook automation,
For each email there is a related Excel file with the name of file equal to the tblTempShipNotice.Adjudicator.
Do you mean the file name will be Something like: Karen Smit.xlsx ?

But where are the files stored exactly ? The full path of the file is needed to add an attachment.
Side notes about the sample database you provided in your earlyer post:

Tables arn't normalized (no primary key, no foreign key),  there are no Relationship between your tables, and no referential integrity.
I suggest you document yourself about databases design, this will help your for futur use.
Avatar of shieldsco

ASKER

The actual db has primary keys
Yes the file name would be in the form of Karen Smit.xlsx and the files are located on a network drive.... U:\QIC Demo Notices DB\Exports
Still, we Don't know where the files to be attached are.

In my otinion, it will be better to add a column in your tblTempShipNotice table, with the full path of files.
This way you won't mix several infos into one. Someone's name is not a file name, neither a file path.
the tblTemShipNotice table has the file name excluding xlsx in a field named Adjudicator
Yeah, but no path.

And building the path from an hard-coded string isn't a good idea, as that will mean if for whataver reasons, the file are moved somewhere else, the code must be updated, and the application deployed again.
While if the path are written in a table, only the table need to be updated.

Also, with networks, it is better to provide a UNC path, as Nothing can ensure you that the drive letter will be the same on another computer.
I would change the hard code path with CurrentProject.Path & "\Exports\" so I can move the DB to any location without changing code
ASKER CERTIFIED SOLUTION
Avatar of Fabrice Lambert
Fabrice Lambert
Flag of France 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
Works great.. thanks for all your help... I think I got the points right this time.
Just as a side note, you don't need the GetCCadresses() function as the solution uses Duane Hookom's Concatenate() Function instead.  So to cleanup your code would might wish to delete it so when you are reviewing your code in a few months/years you are confused.
Thanks... I did