Home > Enterprise >  Send Email to List with Tables/Ranges based on Each User in List
Send Email to List with Tables/Ranges based on Each User in List

Time:12-08

I am currently trying to figure out how to make a workbook that can do the following:

  • Send an email to each user in a list (MailInfo - sheet1 - has two columns. A = Users, B = Email addresses
  • Attach rows from four sheets with rows only relevant to them (Columns A:H) (Users to email are in sheet 1 column A, and they are listed in column H in the other 4 sheets. Currently just 4 sheets that have ranges)

What I am trying to accomplish is that the code loops through the agent list in Sheet 1 and then adds the tables into the body of the email with just the rows that are relevant to them.

My challenge is, I checked through the Ron de Bruin documentation, and I'm able to create emails with full ranges/tables, but I don't think they work for what I have in mind. As I am piecing the bits together, I think I am overcomplicating it. I've provided the code below as a reference. It at the moment will just open an email for each user with all complete tables.

If anyone could give me some pointers or help me, it would help me greatly.

Current code I was able to get to is the following (from Ron de Bruin's documentation), which allows me to open emails for each row in EmailList 1 (I renamed it to MailInfo) and had to add column B to add the mail addresses. However, I need to figure out the code to enable the filtering of the values in the ranges to each user in column A in MailInfo.

Sub Send_Row_Or_Rows_1()
'For Tips see: http://www.rondebruin.nl/win/winmail/Outlook/tips.htm
'Don't forget to copy the function RangetoHTML in the module.
'Working in Excel 2000-2016
    Dim OutApp As Object
    Dim OutMail As Object
    Dim rng As Range
    Dim rng1 As Range
    Dim Ash As Worksheet
    Dim Cws As Worksheet
    Dim Rcount As Long
    Dim Rnum As Long
    Dim FilterRange As Range
    Dim FieldNum As Integer
    Dim mailAddress As String

    On Error GoTo cleanup
    Set OutApp = CreateObject("Outlook.Application")

    With Application
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    'Set filter sheet, you can also use Sheets("MySheet")
    Set Ash = ActiveSheet

    'Set filter range and filter column (Column with names)
    Set FilterRange = Ash.Range("A1:H" & Ash.Rows.Count)
    FieldNum = 1    'Filter column = A because the filter range start in A

    'Add a worksheet for the unique list and copy the unique list in A1
    Set Cws = Worksheets.Add
    FilterRange.Columns(FieldNum).AdvancedFilter _
            Action:=xlFilterCopy, _
            CopyToRange:=Cws.Range("A1"), _
            CriteriaRange:="", Unique:=True

    'Count of the unique values   the header cell
    Rcount = Application.WorksheetFunction.CountA(Cws.Columns(1))

    'If there are unique values start the loop
    If Rcount >= 2 Then
        For Rnum = 2 To Rcount

            'Filter the FilterRange on the FieldNum column
            FilterRange.AutoFilter Field:=FieldNum, _
                                   Criteria1:=Cws.Cells(Rnum, 1).Value

            'Look for the mail address in the MailInfo worksheet
            mailAddress = ""
            On Error Resume Next
            mailAddress = Application.WorksheetFunction. _
                          VLookup(Cws.Cells(Rnum, 1).Value, _
                                Worksheets("Mailinfo").Range("A1:B" & _
                                Worksheets("Mailinfo").Rows.Count), 2, False)
            On Error GoTo 0

            If mailAddress <> "" Then
                With Ash.AutoFilter.Range
                    On Error Resume Next
                    Set rng = Sheets("SampleTable1").Range("A1:H10").SpecialCells(xlCellTypeVisible)
                    Set rng1 = Sheets("SampleTable2").Range("A1:H10").SpecialCells(xlCellTypeVisible)
                    On Error GoTo 0
                End With

                Set OutMail = OutApp.createitem(0)

                On Error Resume Next
                With OutMail
                    .To = mailAddress
                    .Subject = "Test mail"
                    .HTMLBody = RangetoHTML(rng) & "<br>" & RangetoHTML(rng1)
                    .display  'Or use Send
                End With
                On Error GoTo 0

                Set OutMail = Nothing
            End If

            'Close AutoFilter
            Ash.AutoFilterMode = False

        Next Rnum
    End If

cleanup:
    Set OutApp = Nothing
    Application.DisplayAlerts = False
    Cws.Delete
    Application.DisplayAlerts = True

    With Application
        .EnableEvents = True
        .ScreenUpdating = True
    End With
End Sub
Function RangetoHTML(rng As Range)
' Changed by Ron de Bruin 28-Oct-2006
' Working in Office 2000-2016
    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"

    'Copy the range and create a new workbook to past the data in
    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

    'Publish the sheet to a htm file
    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

    'Read all data from the htm file into RangetoHTML
    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=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile
    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

CodePudding user response:

For each user, consolidate the filtered data from the 4 sheets onto 1 temporary sheet and then use RangeToHtml.

Option Explicit

Sub Send_Row_Or_Rows_1()
    
    Dim wb As Workbook
    Dim wsInfo As Worksheet, ws As Worksheet, wsTmp As Worksheet
    Dim i As Long, lastrow As Long
    Set wb = ThisWorkbook
    
    ' sheets to copy
    Dim data(3) As Worksheet
    Set data(0) = wb.Sheets("SampleTable1")
    Set data(1) = wb.Sheets("SampleTable2")
    Set data(2) = wb.Sheets("SampleTable3")
    Set data(3) = wb.Sheets("SampleTable4")

    ' add a temporary sheet
    Application.DisplayAlerts = False
    For Each ws In Sheets
        If ws.name = "~tmp" Then ws.Delete
    Next
    Set wsTmp = Sheets.Add
    wsTmp.name = "~tmp"
    Application.DisplayAlerts = True
    
    Dim rngCopy As Range
    Dim sName As String, sAddr As String
    Dim n As Long, k As Long, r As Long
    
    ' outlook
    Dim appOut As Object, OutMail As Object
    Set appOut = CreateObject("Outlook.Application")
    
    ' scan users
    Set wsInfo = wb.Sheets("Mail Info")
    With wsInfo
        lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
        
        '  for each user
        For i = 2 To lastrow
            sName = Trim(.Cells(i, "A"))
            sAddr = Trim(.Cells(i, "B"))
            r = 1
            wsTmp.Cells.Clear
            
            ' consolidate each sheet on tmp sheet
            For k = 0 To UBound(data)
                Set ws = data(k)
                ' filter on name in col H 8
                With ws.UsedRange
                     .AutoFilter
                     .AutoFilter 8, sName ' col H
                     Set rngCopy = .SpecialCells(xlCellTypeVisible)
                     rngCopy.Copy wsTmp.Cells(r, 1)
                     If r > 1 Then wsTmp.Rows(r).Delete ' leave 1 header
                     r = wsTmp.Cells(ws.Rows.Count, "A").End(xlUp).Row   2 ' leave blank line
                     .AutoFilter
                End With
            Next
    
            ' email sheet
            If r > 1 Then
                Set OutMail = appOut.createitem(0)
                With OutMail
                    .To = sAddr
                    .Subject = "Test Mail to " & sName
                    .HTMLBody = RangetoHTML(wsTmp.UsedRange)
                    .display  'Or use Send
                End With
 
                Set OutMail = Nothing
                n = n   1
            End If
        Next
        
    End With
    
    Application.DisplayAlerts = False
    'ws.Sheets("~tmp").Delete
    Application.DisplayAlerts = True
    
    MsgBox n & " emails sent", vbInformation
End Sub
  • Related