Sub CreateEmails()
Dim OutApp As Object, OutMail As Object, v As Variant, i As Long, rng As Range
v = Range("A2", Range("A" & Rows.Count).End(xlUp)).Resize(, 2).Value
Set OutApp = CreateObject("Outlook.Application")
With CreateObject("scripting.dictionary")
For i = LBound(v) To UBound(v) 'loops through rows
If Not .exists(v(i, 1)) Then
.Add v(i, 1), Nothing
With ActiveSheet
.Range("A1").AutoFilter 1, v(i, 1)
Set rng = .AutoFilter.Range
Set OutMail = OutApp.CreateItem(0)
With OutMail
.To = v(i, 2)
.Subject = Range("K1").Value & " Invoice " & v(i, 1)
.HTMLBody = "Insert your message here." & "<br>" & "More message"
.Display
.Attachments.Add Range("C2").Value
End With
End With
End If
Next i
ActiveSheet.Range("A1").AutoFilter
End With
End Sub
Function RangetoHTML(rng As Range)
Dim fso As Object
Dim ts As Object
Dim TempFile As String
Dim TempWB As Workbook
TempFile = Environ$("temp") & "\" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
rng.Copy
Set TempWB = Workbooks.Add(1)
With TempWB.Sheets(1)
.Cells(1).PasteSpecial Paste:=8
.Cells(1).PasteSpecial xlPasteValues, , False, False
.Cells(1).PasteSpecial xlPasteFormats, , False, False
.Cells(1).Select
Application.CutCopyMode = False
On Error Resume Next
.DrawingObjects.Visible = True
.DrawingObjects.Delete
On Error GoTo 0
End With
With TempWB.PublishObjects.Add( _
SourceType:=xlSourceRange, _
Filename:=TempFile, _
Sheet:=TempWB.Sheets(1).Name, _
Source:=TempWB.Sheets(1).UsedRange.Address, _
HtmlType:=xlHtmlStatic)
.Publish (True)
End With
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
RangetoHTML = ts.readall
ts.Close
RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", "align=left x:publishsource=")
TempWB.Close savechanges:=False
Kill TempFile
Set ts = Nothing
Set fso = Nothing
Set TempWB = Nothing
End Function