Sub Autofilter_1()
Dim MailBody As Range
'Turn Off autofilter if on
ActiveSheet.AutoFilterMode = False
Set mWs = ThisWorkbook.Worksheets("Sheet1")
'Get this workbook name to name the attachment as this workbook and date
Nme = (Left(ThisWorkbook.Name, Len(ThisWorkbook.Name) - 5))
'Set email address as range for first loop to run down
Set rng = Range(Range("E2"), Range("E" & Rows.Count).End(xlUp))
For Each cell In rng
If cell.Value <> "" Then
If Not cell.Offset(0, 2).Value = "yes" Then
'Add New Workbook
Set MailWb = Workbooks.Add
'Activate the main page and filter
mWs.Activate
Worksheets("Sheet1").Range("A1").AutoFilter Field:=5, Criteria1:=cell.Value
'Copy the filter rows to the new workbook including the header
With ActiveSheet.AutoFilter.Range.Offset(0, 0)
.Copy MailWb.Worksheets("Sheet1").Range("A1")
End With
'Use visible cells property so only autofiltered cell rows are changed
For Each dwn In rng.SpecialCells(xlCellTypeVisible)
rng.Offset(0, 2).Value = "yes"
Next
'Turn off autofilter
ActiveSheet.AutoFilterMode = False
'Mail header parameters
MailTo = cell.Value 'column E
mailcc = cell.Offset(0, -3).Value
MailSubject = "Subject?"
'Autofit the copied rows on the new sheet
With MailWb.Worksheets("Sheet1")
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set mailRng = .Range(.Cells(1, 1), .Cells(lRow, 6))
.Range("A1:F2").Columns.AutoFit
End With
'Add mail intro
MsgStr = "Hi" & cell.Offset(0, 1).Value _
& "<br><br> Please see attached "
'Save the new workbook as an xlsx file
TempFilePath = Environ$("temp") & "\"
TempFileName = Nme & " " & Format(Now, "dd-mmm-yy h-mm-ss") & ".xlsx"
'Add mail intro
MsgStr = "Hi" & cell.Offset(0, 1).Value _
& vbNewLine & vbNewLine & "Please see attached: " _
& vbNewLine & TempFileName
'Create mail
Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With MailWb
.SaveAs TempFilePath & TempFileName, FileFormat:=51
On Error Resume Next
With OutMail
.to = MailTo
.CC = mailcc
.BCC = ""
.Subject = MailSubject
.Body = MsgStr
.Attachments.Add MailWb.FullName
.Display
'.Send 'or use .Display
End With
On Error GoTo 0
.Close savechanges:=False
End With
'Delete the file you have sent
Kill TempFilePath & TempFileName & FileExtStr
End If
End If
MailTo = ""
MailSubject = ""
Next
End Sub