UDF To Send Email From Excel Worksheet
Here is a great macro that is actually a UDF (User Defined Function) to send messages (using Outlook) directly from the Excel worksheet.
Function SendMessage(Msg As String, Subject As String, EmailTo As String, _ Optional EmailCC As String, Optional EmailBCC As String, _ Optional Attachment As String, Optional Importance As String) ' ' this will only set up the email for display, if you need to send ' in bulk use mail merge ' Dim Outlook As Outlook.Application Dim OutlookMsg As Outlook.MailItem Dim OutlookRecip As Outlook.Recipient Dim OutlookAttach As Outlook.Attachment ' create outlook session Set Outlook = CreateObject("Outlook.Application") ' create msg Set OutlookMsg = Outlook.CreateItem(olMailItem) With OutlookMsg ' set basic params .Subject = Subject .HTMLBody = Msg Set OutlookRecip = .Recipients.Add(EmailTo) OutlookRecip.Type = olTo ' add cc's (if any) If EmailCC <> "" Then Set OutlookRecip = .Recipients.Add(EmailCC) OutlookRecip.Type = olCC End If ' add bcc's (if any) If EmailBCC <> "" Then Set OutlookRecip = .Recipients.Add(EmailBCC) OutlookRecip.Type = olBCC End If ' add attachments If Attachment <> "" Then Set OutlookAttach = .Attachments.Add(Attachment) End If ' set importance If Importance <> "" Then If Importance = "High" Then .Importance = olImportanceHigh ElseIf Importance = "Low" Then .Importance = olImportanceLow Else: .Importance = olImportanceNormal End If End If ' resolve names For Each OutlookRecip In .Recipients OutlookRecip.Resolve Next OutlookRecip .Display ' .send End With Set Outlook = Nothing Set OutlookRecip = Nothing Set OutlookAttach = Nothing Set OutlookMsg = Nothing End Function
To use, paste the above code into a standard Excel VB module, then use in the worksheet like this:
=SendMessage(A1,A2,A3,A4,A5,A6,A7)
If you put the code in your PERSONAL.XLS file, you may have to qualify the function like this:
=PERSONAL.XLS!SendMessage(A1,A2,A3,A4,A5,A6,A7)
Where A1 contains a text string you want to send as the Body, A2 contains a text string with the email subject, A3 contains an email address or comma-separated list of email addresses (or a name resolvable in Outlook), A4 contains the (optional) email CC, A5 contains the (optional) email BCC, A6 contains the (optional) full path and filename of an attachment you want to send, and A7 contains a text string with the email importance (High, Low or Normal)
Don't forget to set a reference to the Outlook object library. (see the Binding page for help setting up references to object libraries).
LAST UPDATED: March 30, 2008