Hi there
I've managed to get the below VBA working from a very old (2010) thread. It creates emails to recipients for each row in a spreadsheet, customises the email content (with the recipients name) and also attaches a file based on a file path in column E of the sheet.
I've tweaked it slightly, and all is working perfectly, except it attaches the attachments multiple times to each email (i.e. if I have 10 rows of recipients on the spreadsheet it attaches the attachment in column E and the .htm file x10 times in each email it generates, rather than just once based on that particular row in the sheet. Any ideas on what I need to change in the code to overcome this please?
Any help would be very much appreciated! TIA
I've managed to get the below VBA working from a very old (2010) thread. It creates emails to recipients for each row in a spreadsheet, customises the email content (with the recipients name) and also attaches a file based on a file path in column E of the sheet.
I've tweaked it slightly, and all is working perfectly, except it attaches the attachments multiple times to each email (i.e. if I have 10 rows of recipients on the spreadsheet it attaches the attachment in column E and the .htm file x10 times in each email it generates, rather than just once based on that particular row in the sheet. Any ideas on what I need to change in the code to overcome this please?
VBA Code:
Sub Email_Docs()
Dim OutApp As Object
Dim OutMail As Object
Dim sh As Worksheet
Dim cell As Range, FileCell As Range, rng As Range
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Set sh = Sheets("Sheet1")
Set OutApp = CreateObject("Outlook.Application")
For Each cell In sh.Columns("B").Cells.SpecialCells(xlCellTypeConstants)
'Enter the file names in the E column in each row
Set rng = sh.Cells(cell.Row, 1).Range("E1:E1")
If cell.Value Like "?*@?*.?*" And _
Application.WorksheetFunction.CountA(rng) > 0 Then
Set OutMail = OutApp.CreateItem(0)
'Need to include Your_Name_Here in the body of the text to personalize
strbody = GetBoiler(cell.Offset(0, 2))
strbody = Replace(strbody, "Your_Name_Here", cell.Offset(0, -1).Value, Compare:=vbTextCompare)
With OutMail
.To = cell.Value
.Subject = cell.Offset(0, 1)
.HTMLBody = strbody
For Each FileCell In rng.SpecialCells(xlCellTypeConstants)
If Trim(FileCell) <> "" Then
If Dir(FileCell.Value) <> "" Then
.Attachments.Add FileCell.Value
End If
End If
Next FileCell
.Display
End With
Set OutMail = Nothing
End If
Next cell
Set OutApp = Nothing
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Function GetBoiler(ByVal sFile As String) As String
Dim fso As Object
Dim ts As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(sFile).OpenAsTextStream(1, -2)
GetBoiler = ts.readall
ts.Close
End Function
Any help would be very much appreciated! TIA