Here is a UDF for Excel that
attaches three files to an email, and you specify the fourth one in
the function call. Paste this into a new module:
Dim bWeStartedOutlook As Boolean
Function SendMail(strRecip As String, strFilePath As String)
On Error GoTo ExitProc
Dim olApp As Object
Dim Msg As Object
Set olApp = GetOutlookApp
If Not olApp Is Nothing Then
Set Msg = olApp.CreateItem(0)
With Msg
.To = strRecip
.Subject = "Files you requested"
With .Attachments
.Add "C:\MyFile1.xls"
.Add "C:\MyFile2.xls"
.Add "C:\MyFile3.xls"
.Add strFilePath
End With
' Outlook Object Model Guard triggered
If Not .Recipients.ResolveAll Then
MsgBox "I don't understand that recipient."
.Display
Else
.Send
End If
End With
End If
ExitProc:
If bWeStartedOutlook Then
olApp.Quit
End If
Set olApp = Nothing
Set Msg = Nothing
End Function
Function GetOutlookApp() As Object
' returns a reference to Outlook to the calling sub
On Error Resume Next
Set GetOutlookApp = GetObject(, "Outlook.Application")
On Error GoTo 0
If GetOutlookApp Is Nothing Then
Set GetOutlookApp = CreateObject("Outlook.Application")
bWeStartedOutlook = True
Exit Function
End If
End Function
To use in your code:
Call SendMail("John Smith", "C:\MyFile4.xls")
' or
Call SendMail("jsmith@...", "C:\MyFile4.xls")
I changed it to late binding so it can just be cut and pasted by
anyone. You can even use it from the worksheet: Just set up one
column of email addresses and a second column with the unique fourth
attachment path and filename for that email address and
enter "=SendMail(A1,B1)" into a cell on the worksheet.
Note that the code will trigger the OMG (object model guard) when
calling the ResolveAll Method. You can avoid this by using email
addresses (which always resolve) instead of address book names, just
replace
' Outlook Object Model Guard triggered
If Not .Recipients.ResolveAll Then
MsgBox "I don't understand that recipient."
.Display
Else
.Send
End If
with
.Send
Of course, if you wanted to do this programmatically, you need a way
to figure out which attachment to attach for a particular recipient.