I have written a probably fairly basic macro which calls up the new message dialogue in MS Outlook. It then populates that dialogue with data contained within a spreadsheet (see code below). It does work well, in that whichever e-mail address the user selects (which therefore makes that cell the active cell), VBA will use that cell as the “to” field and then “cc” in the value of the cell one to the right (another e-mail address). Unfortunately this has to be done for each and every person who needs to be e-mailed, often up to 40 or 50 people.
What I’d like to do (and what I’ve failed at so far) is have VBA loop through each row with values in, and enter those values into the relevant Outlook field, ending if there is an error. The only fields which will change are the “to” and “cc” fields, as the e-mail address the e-mail is sent from never changes, nor does the body or subject. In short, I’m sending a e-mail to each person in a table.
I’ve tried to do it but at best all I can get VBA to do is start an endless loop of opening the new message dialogue, with no values entered. Does anybody have any pointers?
The source table:
My current code:
What I’d like to do (and what I’ve failed at so far) is have VBA loop through each row with values in, and enter those values into the relevant Outlook field, ending if there is an error. The only fields which will change are the “to” and “cc” fields, as the e-mail address the e-mail is sent from never changes, nor does the body or subject. In short, I’m sending a e-mail to each person in a table.
I’ve tried to do it but at best all I can get VBA to do is start an endless loop of opening the new message dialogue, with no values entered. Does anybody have any pointers?
The source table:
Enter Name Here | Supervisor | E-mail address | Supervisor e-mail address |
Value entered here is the source of the formula on the right | Name, result of INDEX formula | This is the 'to' field (result of INDEX formula) | This is the 'cc' field (result of INDEX formula) |
My current code:
VBA Code:
Sub Email_Timesheet()
On Error Resume Next
Dim OutApp As Variant
Dim OutMail As Variant
Set OutApp = CreateObject("Outlook.Application")
OutApp.Session.Logon
Set OutMail = OutApp.CreateItem(0)
On Error Resume Next
With OutMail
.SentOnBehalfOfName = "sharedinbox@example.com" 'this is the "from" field
.To = Range(Selection.Address)
.CC = Range(Selection.Address).offset(, 1) 'this enters the value in the column one to the right of the selected e-mail address
.Subject = "Late Timesheet"
.body = Range("J1") 'this references the cell where the body of the e-mail is written
On Error Resume Next
On Error GoTo 0
.Save
.Display
'.send '<<<<<to send without reviewing first, remove the "'"
End With
On Error GoTo 0
Set OutMail = Nothing
Set OutApp = Nothing
End Sub