Sub CommandButton1_Click()
Dim Address As Variant
Dim Dict As Object
Dim DstWkb As Workbook
Dim EmailInfo As Variant
'Dim Filename As String
Dim i As Long, j As Long
Dim NewWkb As Workbook
Dim olApp As Object
Dim Rng As Range
Dim SrcWkb As Workbook
Dim SrcWks As Worksheet
Dim SheetName As String
Dim SheetNames As Variant
' Filename = ActiveWorkbook.FullName
Set Rng = Range("A1").CurrentRegion
' EmailInfo starts in column "B" to the last column used.
Set EmailInfo = Intersect(Rng, Rng.Offset(1, 0))
' Copy the sheet names and email addresses into arrays for faster processing.
SheetNames = EmailInfo.Columns(1).Cells.Value
EmailInfo = Intersect(EmailInfo, EmailInfo.Offset(0, 1)).Value
' Create an associative array to hold the email addresses and the sheet names for each one.
Set Dict = CreateObject("Scripting.Dictionary")
Dict.CompareMode = vbTextCompare
' Collect email addresses and sheet names associated with each address.
For i = 1 To UBound(EmailInfo, 1)
For j = 1 To UBound(EmailInfo, 2)
SheetName = SheetNames(i, 1)
Address = EmailInfo(i, j)
If Address <> "" Then
If Not Dict.Exists(Address) Then
Dict.Add Address, SheetName
Else
SheetName = Dict(Address) & "," & SheetName
Dict(Address) = SheetName
End If
End If
Next j
Next i
' Open the workbook with the sheets to be copied as email attachments.
Set SrcWkb = ThisWorkbook
Set olApp = CreateObject("Outlook.Application")
For Each Address In Dict.Keys
' Create a new workbook to be used as the attachment with Sheet1, which is later deleted
Set DstWkb = Workbooks.Add(xlWBATWorksheet)
' Copy all the sheets associated with an email to the new workbook.
SheetNames = Split(Dict(Address), ",")
For i = 0 To UBound(SheetNames, 1)
SrcWkb.Worksheets(SheetNames(i)).Copy After:=DstWkb.Worksheets(DstWkb.Worksheets.Count)
ActiveSheet.Name = SheetNames(i)
Next i
' Turn off prompts
Application.DisplayAlerts = False
' Delete Sheet1 so that workbook only contains sheets w scout information.
Sheets("Sheet1").Delete
' Save the new workbook.
DstWkb.SaveAs Filename:="Workbook2.xlsx"
' Turn prompts back on
Application.DisplayAlerts = True
' Email Subject line.
SubjectLine = "Test"
' Email Message.
MsgBody = "Hello,"
MsgBody = MsgBody & vbCrLf & vbCrLf
MsgBody = MsgBody & "This is a test"
MsgBody = MsgBody & vbCrLf
MsgBody = MsgBody & "This is a test"
MsgBody = MsgBody & vbCrLf
MsgBody = MsgBody & "This is a test"
MsgBody = MsgBody & vbCrLf & vbCrLf
MsgBody = MsgBody & "This is a test"
MsgBody = MsgBody & vbCrLf & vbCrLf
' Email the workbook as an attachment.
With olApp.CreateItem(0)
.To = Address
.Subject = SubjectLine
.Body = MsgBody
.Attachments.Add DstWkb.FullName, 1, 1
.Send
End With
' Close the new workbook
DstWkb.Close SaveChanges:=False
' Then delete it
Kill "Workbook2.xlsx"
Next Address
' Close the source workbook whose sheets were copied
' SrcWkb.Close SaveChanges:=False
End Sub