【问题标题】:Using VBA to build emails from Excel that combine email body when addresses duplicate使用 VBA 从 Excel 构建电子邮件,当地址重复时结合电子邮件正文
【发布时间】:2019-04-30 21:38:40
【问题描述】:

首先,我对 VBA 很陌生。还在学习,所以我可能会犯一些明显的错误。

我正在尝试使用 Excel 电子表格构建电子邮件,我从中提取信息以填充电子邮件的收件人、主题和正文。这些将让销售人员为他们的客户查看信息。我需要每封电子邮件都基于客户并发送给相应的销售代表。一些客户拥有多行信息,而另一些客户拥有多行信息,而一些销售人员则拥有重叠的客户。

我发现并尝试编辑的代码是(据我所知)基于电子邮件地址构建电子邮件。因此,我最终收到一封电子邮件,其中在收件人行中有一个销售人员,并且正文包含专门针对该销售人员的所有客户。同时,主题行仅吸引电子邮件要显示的一位客户。

对此的任何帮助都是天赐之物。我正在尝试将 4-6 小时的工作量减少到 1 小时以下。

每当我尝试对代码进行更改以使其基于客户而不是电子邮件地址时,我要么最终破坏了代码,要么不构建电子邮件,而是以某种方式将过滤器应用于过滤器的电子表格与更改之前进入电子邮件的信息相同。

我觉得可能需要更多信息,因为我发现这比看起来要复杂得多,但这可能是我想多了。我试图将这篇文章限制在相关信息上,但如果我需要提供更多信息,我当然会提供。我已经为此绞尽脑汁好几个星期了。

我尝试了各种 If And/Then 语句来尝试使代码查看客户列而不是电子邮件列,但我找不到任何有效的组合。我在下面发布的代码是我设法在某种程度上开始工作的代码。由于我尝试了这么多变体,我不知道最好的错误是什么。所以希望这至少不会太混乱。

*编辑:代码需要 A 列中的一列名称,据我了解,这应该是“为此名称使用 B 列中的地址创建电子邮件”的条件。但它似乎正在做的是使用 B 列中的地址作为条件创建一封电子邮件。因此,A 中与 B 中的地址匹配的任何客户行都会被扔到同一封电子邮件中。我有点需要反过来。 A 列的每位客户向 B 列中列出的任何电子邮件地址发送一封电子邮件。

Edit2:源信息看起来像这样:

+----------------+---------------------+---------+--------------+
|     Customer   |       Email         | Subj Ln |  Email Body  |
+----------------+---------------------+---------+--------------+
| Customer 1     | sales1@address.com  | info    |     info     |
| Customer 2     | sales2@address.com  | info    |     info     |
| Customer 2     | sales2@address.com  | info    |     info     |
| Customer 2     | sales2@address.com  | info    |     info     |
| Customer 3     | sales2@address.com  | info    |     info     |
| Customer 4     | sales3@address.com  | info    |     info     |
| Customer 4     | sales3@address.com  | info    |     info     |
| Customer 5     | sales1@address.com  | info    |     info     |
| Customer 6     | sales4@address.com  | info    |     info     |
+----------------+---------------------+---------+--------------+

因此,代码应该查看客户列(A 列)并查找唯一实例,然后在电子邮件列(B 列)中生成具有适当电子邮件地址的电子邮件。每一个都应该是一个单独的电子邮件,当电子邮件地址对客户来说是唯一的时,它会这样做。因此,在上面的示例中,客户 6 收到一封单数电子邮件给 sales4。电子邮件会生成适当的主题行和电子邮件正文。但是,客户 1 将生成一封带有相应主题 Ln 和电子邮件正文(对于客户 1)的电子邮件,并且它还将具有相应的 sales1 电子邮件地址。但由于 sales1 也有客户 5,因此客户 5 的电子邮件正文信息包含在客户 1 电子邮件中。当我需要客户 5 成为单独的电子邮件时。

Edit3:我在下面添加了以下段落作为评论,因为我不确定哪个是获得它的可见性的最佳方式。

我一直在玩代码,并认为我可能发现了一些我以前不完全理解的东西。我不确定我是否仍然这样做,但我认为我有更好的理解。 -- 看起来代码正在创建一个用于构建电子邮件正文的过滤器。它正在过滤 B 列(电子邮件)以获取唯一值并基于此创建电子邮件。我想如果我可以更改过滤器代码以过滤 A 列并使用 B 列构建电子邮件,那么我想我会得到我想要的。我只是不知道如何使它工作。

我希望我很清楚。这让我感到非常困惑和不知所措,但我希望这是有道理的。另外,我希望我的格式是正确的。

Sub Send_Row_Or_Rows_2()

Dim OutApp As Object
Dim OutMail As Object
Dim rng 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

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 e-mail addresses)
Set FilterRange = Ash.Range("A1:AY" & Ash.Rows.Count)
FieldNum = 2    'Filter column = B because the filter range start in 
column 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

        'If the unique value is a mail addres create a mail
        If Cws.Cells(Rnum, 1).Value Like "?*@?*.?*" Then

            With Ash.AutoFilter.Range
                On Error Resume Next
                Set rng = .SpecialCells(xlCellTypeVisible)
                On Error GoTo 0
            End With

            Set OutMail = OutApp.CreateItem(0)

            On Error Resume Next
            With OutMail
                .To = Cws.Cells(Rnum, 1).Value
                .Subject = Ash.Cells(Rnum, 3) & " Bond Review " & Date
                .HTMLBody = RangetoHTML(rng)
                .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)

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

Public Function EOMonth(dInput As Date)

LastDayOfMonth = DateSerial(Year(dInput()), Month(dInput() + 1), -1)

End Function

【问题讨论】:

  • 您为什么在 Excel 中执行此操作而不是在 Powershell 中执行此操作?您如何将数据提取到 Excel 中?对我来说,这似乎更适合一个脚本,该脚本在每个指定时间段运行,并在将更多客户添加到您使用的任何数据库系统时向销售人员发送电子邮件更新。
  • 您能否清除这部分“同时主题行仅吸引电子邮件要显示的一位客户。”?您能否提供有关某些源数据行的信息,应如何处理以正确发送电子邮件,以及您得到的是什么?
  • @RileyCarney 我不熟悉 Powershell。直到几周前,我什至不熟悉 VBA。我对编码或任何编码软件一开始就知之甚少。数据首先在 Excel 电子表格中提供给我。我正在尝试提取这些数据并将其放入包含正确信息的单独电子邮件中。只要电子邮件地址都是唯一的,该脚本就会以我需要的格式提取我需要的信息。一旦复制了一封邮件,它就会向该地址创建一封电子邮件,其中包含与该地址相关的所有客户信息,而不是单独的电子邮件。
  • @VanNg 我在原始帖子中进行了编辑,希望能更清楚地了解源信息。 - 主题行为为该电子邮件提取的第一个客户提取正确的对应行。这很好,并且当只有一位客户拉出电子邮件时可以按预期工作。一旦多个客户被扔进同一封电子邮件(我不想要),那么它只会在主题行中显示一个客户。我认为在我的原始帖子中提及主题行可能毕竟是不重要的信息。它正在做它应该做的事情。
  • @Olly0206 我今晚下班回家后会为你整理一些东西。 :)

标签: excel vba


【解决方案1】:

我已经写过很多次这样的代码了——基本模板实际上在我的github上

代码:

Option Explicit


Sub LoopOverData()
Dim STbl As ListObject
Dim LastRow As Long
Dim WB As Workbook
Dim i As Long
Dim WS As Worksheet
Dim tblwsname As String


    Set WB = ThisWorkbook


    tblwsname = WB.Names("TblWSName").RefersToRange.Value2
    Set WS = WB.Sheets(tblwsname)
    Set STbl = WS.ListObjects("EmailDataTable")


    LastRow = STbl.ListRows.Count


    For i = 1 To LastRow
         WB.Names("IterationNumber").RefersToRange.Value2 = i
         Application.Calculate
         Call CreateEmail
    Next i



End Sub





Sub CreateEmail()
' This macro is for the pricing confirm e-mail
    Dim outApp As New Outlook.Application
    Dim OutMail As Object
    Dim Attchmnt As String
    Dim Signature As String
    Dim WB As Workbook
    Set WB = ThisWorkbook
   Attchmnt = WB.Names("Attachment").RefersToRange.Value2
   'We keep the file path for the attachment we're sending in Excel, for easy editing. Look in name manager to find it.

    Application.EnableEvents = False
     Application.ScreenUpdating = False

    ' We don't need the screen to flicker while the macro is running - it speeds things up.
    Set OutMail = outApp.CreateItem(0)
    'Signature = OutMail.Body
    On Error Resume Next
    With OutMail
    .To = WB.Names("to").RefersToRange.Value2
   .CC = WB.Names("cc").RefersToRange.Value2
   .BCC = WB.Names("bcc").RefersToRange.Value2
   .Subject = WB.Names("Subject").RefersToRange.Value2
   .Body = WB.Names("Body").RefersToRange.Value2
   .display
   End With

   If Attchmnt = "" Then
   Else
   OutMail.Attachments.Add Attchmnt
   End If

   'OutMail.send
   'Remove this comment to directly send. Not recommended.

   On Error GoTo 0
End Sub

设置:您基本上创建了一个“示例电子邮件”,然后使用 =index(Range, IndexNum) 来确定您当前正在处理的项目。 IndexNum 是一个返回到基本索引的命名范围,代码将对其进行更改。

因此,随着索引中的每个数字被移动,所有公式都会更新为需要写入的新电子邮件。然后它调用电子邮件生成过程,并创建(但不发送)所需的电子邮件。这是为了让您有机会在发送之前查看电子邮件。

您需要启用 Microsoft Outlook 16.0 对象库。

发送我丢失的信息可能有一些规则 - 如果是这种情况,我建议使用一些公式或电源查询来进行压缩

【讨论】:

  • 此代码不会创建唯一的电子邮件,仅针对每一行
  • 正确 - 但此时它变成了一个公式问题,虽然我不太确定需要如何合并,但这让我很难回答。无论哪种方式,公式方面都是代码中相对简单的部分
【解决方案2】:

试试这个,实际上它会生成所需数量的电子邮件。如果OK,我会清除代码

Option Explicit

Sub Send_Row_Or_Rows_2()

    Dim OutApp As Object
    Dim OutMail As Object
    Dim rng 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


    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 e-mail addresses)
    Set FilterRange = Ash.Range("A1:BY" & Ash.Rows.Count)
    FieldNum = 2    'Filter column = B because the filter range start in     Column A
    'FieldNum = 2

    Columns("A:B").Select
    Selection.Copy

    ActiveSheet.Paste

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


    Columns("A:B").Select
    Application.CutCopyMode = False
    ActiveSheet.Range("$A$1:$B$10").RemoveDuplicates Columns:=Array(1, 2), Header _
        :=xlYes

    '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:=1, _
                                   Criteria1:=Cws.Cells(Rnum, 1).Value

            FilterRange.AutoFilter Field:=2, _
                                   Criteria1:=Cws.Cells(Rnum, 2).Value

            'If the unique value is a mail addres create a mail
            If Cws.Cells(Rnum, 2).Value Like "?*@?*.?*" Then

                With Ash.AutoFilter.Range
                    On Error Resume Next
                    Set rng = .SpecialCells(xlCellTypeVisible)
                    On Error GoTo 0
                End With

                Set OutMail = OutApp.CreateItem(0)

                On Error Resume Next
                With OutMail
                    Debug.Print "to: " & .to & " subj: " & .Subject & " body:" & .htmlbody
                    .to = Cws.Cells(Rnum, 2).Value
                    .Subject = Ash.Cells(Rnum, 3) & " Bond Review " & Date
                    .htmlbody = RangetoHTML(rng)
                    .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)

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

Public Function EOMonth(dInput As Date)

LastDayOfMonth = DateSerial(Year(dInput()), Month(dInput() + 1), -1)

End Function

【讨论】:

  • 我不确定它做了什么,但它做了一些事情。我没有收到错误或任何错误,看起来它循环了整个代码,但它没有生成任何电子邮件或进行任何我能找到的更改。我真的不确定发生了什么,但据我所知没有任何改变。
  • "每行一个。650 行。650 封电子邮件。" - 上面的代码做同样的事情吗?它还生成了 650 封电子邮件?或者它没有产生任何东西?
  • 什么也得不到。没有电子邮件。没什么。看起来代码正在做某事。但无论它在做什么都是背景,所以你实际上看不到任何结果。
【解决方案3】:

我就是这样使用的,首先你需要将你的文本转换为表格并将其命名为 CustomersTbl 或使用

LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' get last row
Set Rng = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, 4))

而不是

Set rng = ws.Range("CustomersTbl")

这是一个代码

Sub Send_Row_Or_Rows_2()
' reference Microsoft Scripting Runtime
Dim OutApp As Object, OutMail As Object, dict As Object
Dim tKey(0 To 3, 0 To 1) As Variant
Dim rng As Range
Dim ws As Worksheet

On Error GoTo cleanup
Set OutApp = CreateObject("Outlook.Application")
With Application
    .EnableEvents = False ' speedup Application, disable events
    .ScreenUpdating = False ' prevent flashing, disable screen
End With

Set ws = ThisWorkbook.Worksheets("Sheet1") ' set shortest variable for worksheet
Set dict = CreateObject("Scripting.Dictionary") ' set object for unique values
Set rng = ws.Range("CustomersTbl") ' get range to variable
'LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row ' get last row
'Set Rng = ws.Range(ws.Cells(1, 1), ws.Cells(LastRow, 4)) 'get range to variable
For Each cRow In rng ' create unique dictionary
    i = i + 1 ' increment
    strCustomer = rng(i, 1)
    strEmail = rng(i, 2)
    strSubj = rng(i, 3)
    strBody = rng(i, 4)
    If dict.Exists(strCustomer) Then ' if dublicate
        Dim tempArr() As Variant
            tempArr() = dict(strCustomer)
                If UBound(tempArr, 2) > 0 Then ' if not nothing
                    If Not IsEmpty(tempArr(0, 1)) Then ' if second element empty
                        sCount = UBound(tempArr, 2) + 1
                    Else
                        sCount = UBound(tempArr, 2)  ' as is empty array
                    End If
                End If
                    ReDim Preserve tempArr(0 To 3, 0 To sCount) ' redim array to next array size
                        tempArr(0, sCount) = strCustomer 'fill array element
                        tempArr(1, sCount) = strEmail 'fill array element
                        tempArr(2, sCount) = strSubj 'fill array element
                        tempArr(3, sCount) = strBody 'fill array element
            dict(strCustomer) = tempArr ' put array to dictionary by unique name
    Else
        tKey(0, 0) = strCustomer 'fill array element
        tKey(1, 0) = strEmail 'fill array element
        tKey(2, 0) = strSubj 'fill array element
        tKey(3, 0) = strBody 'fill array element
            dict.Add strCustomer, tKey ' create unique name
    End If
Next cRow ' loop next row
' now dict contains only unique elements, lets loop throught them
For Each UniqueCustomer In dict ' for each unique element
countEmails = UBound(dict(UniqueCustomer), 2) ' count emails of unique group
    For i = 0 To countEmails ' loop each email in group
        strCustomer = dict(UniqueCustomer)(0, i)
        strEmail = dict(UniqueCustomer)(1, i)
        strSubj = dict(UniqueCustomer)(2, i)
        strBody = dict(UniqueCustomer)(3, i)
        If Not IsEmpty(strCustomer) Then ' if element not empty create email
            Set OutMail = OutApp.CreateItem(0)
                    On Error Resume Next
                    With OutMail
                        .To = strEmail
                        .Subject = strSubj
                        .HTMLBody = strBody
                        .Display  'Or use Send
                    End With
                    On Error GoTo 0
            Set OutMail = Nothing
        Else
            GoTo sNext
        End If
        Stop
sNext:
    Next I ' next email
Next UniqueCustomer 'next unique

cleanup:
Set OutApp = Nothing

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With
End Sub

【讨论】:

    【解决方案4】:

    如果我理解正确,您希望根据客户和电子邮件地址的唯一组合发送电子邮件,并为每个唯一组合获取相应的主题行和电子邮件正文。因此,在上面的示例中,我假设由于 customer2 和 Customer4 是重复的,那么您只想为每个客户发送一封电子邮件,并使用在 Cutomer2 或 4 第一次出现时找到的相应主题行和电子邮件正文。

    如果我的假设是正确的,那么下面的代码应该可以完成这项工作。请注意解释每个步骤的 cmets。

    编辑:我忘了提到像我最初那样使用分隔符是有风险的,因为该分隔符可能存在于数据中的某处,并且由该分隔符拆分会影响您的结果。因此,更好的方法(我相信也更干净)如下:

    Option Explicit
    
    Public Sub SendEmails()
    
     Dim objDict As Object
     Dim objWB As Workbook
     Dim objWS As Worksheet
     Dim rngToLookUp As Range
     Dim lngLastRow As Long, i As Long
     Dim arryEmailData As Variant
     Dim objOutlookApp As Object, objOutlookEmail As Object
     Dim varKey As Variant, arryTemp As Variant
    
        Application.ScreenUpdating = False
    
        Set objWB = Workbooks("SomeWBName")
        Set objWS = objWB.Worksheets("SomeWSName")
        lngLastRow = objWS.Cells(objWS.Rows.Count, "A").End(xlUp).Row   'Find last row with data
        Set rngToLookUp = objWS.Range("A2:D" & lngLastRow)              'set range for last row of data
    
        arryEmailData = rngToLookUp.Value2    'Get the email data from the sheet into an array
    
            Set objDict = CreateObject("Scripting.Dictionary")      'set the dicitonary object
            Set objOutlookApp = CreateObject("Outlook.Application") 'set the outlook object
    
    
                For i = LBound(arryEmailData, 1) To UBound(arryEmailData, 1)
                    varKey = Join(Array(arryEmailData(i, 1), arryEmailData(i, 2)), "|") 'Concatenate columns A and B using '|' as a
                                                                                        'delimiter to form a unique Key
    
                    If Not objDict.Exists(varKey) Then
    
                        objDict(varKey) = Array(arryEmailData(i, 2), _
                                                arryEmailData(i, 3), _
                                                arryEmailData(i, 4))
                    End If
    
                    varKey = Empty
    
                Next i
    
                'for each unique key in the dicitonary
                'get the corresponding item which is an array
                'created in the loop above
                On Error GoTo cleanup
                For Each varKey In objDict.Keys
                    arryTemp = objDict.Item(varKey)
                    Set objOutlookEmail = objOutlookApp.CreateItem(0)
                        With objOutlookEmail
                            .To = arryTemp(0)
                            .Subject = arryTemp(1)
                            .Body = arryTemp(2)
                            .Send
                        End With
                    Set objOutlookEmail = Nothing
                    arryTemp = Empty
                Next
    
        MsgBox "All Emails have been sent", vbInformation
    
    cleanup:
            Set objOutlookApp = Nothing
            Application.ScreenUpdating = True
    
    End Sub
    

    原帖:

    Option Explicit
    
    Public Sub SendEmails()
    
     Dim objDict As Object
     Dim objWB As Workbook
     Dim objWS As Worksheet
     Dim rngToLookUp As Range
     Dim lngLastRow As Long, i As Long
     Dim arryEmailData As Variant
     Dim objOutlookApp As Object, objOutlookEmail As Object
     Dim varKey As Variant, arryTemp As Variant
    
        Application.ScreenUpdating = False
    
        Set objWB = Workbooks("SomeWBName")
        Set objWS = objWB.Worksheets("SomeWSName")
        lngLastRow = objWS.Cells(objWS.Rows.Count, "A").End(xlUp).Row   'Find last row with data
        Set rngToLookUp = objWS.Range("A2:D" & lngLastRow)              'set range for last row of data
    
        arryEmailData = rngToLookUp.Value2    'Get the email data from the sheet into an array
    
            Set objDict = CreateObject("Scripting.Dictionary")      'set the dicitonary object
            Set objOutlookApp = CreateObject("Outlook.Application") 'set the outlook object
    
    
                For i = LBound(arryEmailData, 1) To UBound(arryEmailData, 1)
                    varKey = Join(Array(arryEmailData(i, 1), arryEmailData(i, 2)), "|") 'Concatenate columns A and B using '|' as a
                                                                                        'delimiter to form a unique Key
    
                    If Not objDict.Exists(varKey) Then                          'If the key doesn't already exist, then concatenate
                                                                                'the corresponding Email Address, subject line,
                                                                                'and email body using
                                                                                ''|' as a delimiter
                        objDict(varKey) = Join(Array(arryEmailData(i, 2), _
                                                     arryEmailData(i, 3), _
                                                     arryEmailData(i, 4)), "|")
                    End If
    
                    varKey = Empty
    
                Next i
    
                'for each unique key in the dicitonary
                'get the corresponding item
                'split the item into a 3 element array using '|' delimiter that
                'was originally used to concatenate the item in the loop above
                On Error GoTo cleanup
                For Each varKey In objDict.Keys
                    arryTemp = Split(objDict.Item, "|")
                    Set objOutlookEmail = objOutlookApp.CreateItem(0)
                        With objOutlookEmail
                            .To = arryTemp(0)
                            .Subject = arryTemp(1)
                            .Body = arryTemp(2)
                            .Send
                        End With
                    Set objOutlookEmail = Nothing
                Next
    
        MsgBox "All Emails have been sent", vbInformation
    
    cleanup:
            Set objOutlookApp = Nothing
            Application.ScreenUpdating = True
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2011-08-24
      • 1970-01-01
      • 2016-04-12
      • 2017-10-09
      • 2017-12-11
      • 2014-02-14
      • 2017-05-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多