删除之前未解析的收件人

时间:2015-10-15 22:51:18

标签: vba email outlook

很抱歉,如果这令人困惑,我试着尽我所能地解释整个过程......

以下代码是更大代码的一部分,该代码抓取项目中涉及的人员的姓名,并将其添加到名为" myRecipients"的变量中。其大小为Outlook.Recipients,并自动创建通知电子邮件。代码的其他部分似乎正在运行。

代码应删除未解析的名称并将其保存到数组(ToralErrName),以便消息框可以让用户知道他们必须在Outlook邮件消息中手动添加未解析的名称。此代码有效,直到我尝试添加此检查。

问题是,当删除当前收件人时,它会从数组中删除该成员以及" myRecipients"中的当前位置。成为数组中的下一个。所以,当代码进入" Next myRecipient"它会跳过当前位置(这可能是删除当前项目之前的下一个项目)并转到下一个收件人。

有没有人知道如何防止这种情况发生?通常情况下,如果这是一个带有整数值的for循环,那么我只需添加类似" i = i-1"的东西,但我不熟悉如何使用Outlook.Recipients变量进行此操作。感谢您提出任何建议!

    For Each myRecipient In myRecipients
         If Not myRecipient.Resolved Then
             If Not TotalErrName = "" Then
                 TotalErrName = TotalErrName & ", " & myRecipient.Name
             Else
                 TotalErrName = myRecipient.Name
             End If
             myRecipient.Delete 'Delete recipient if they are not found in the address book
         End If
    Next myRecipient

        MsgBox "The following names were not found in the address book and must be added manually: " & TotalErrName

2 个答案:

答案 0 :(得分:1)

通常最好避免在循环其内容时更改集合:一种方法(我也看到A.S.H建议)是将项目添加到另一个集合以供以后处理:

Dim c As New Collection, r, sep

sep = ""
For Each myRecipient In myRecipients
     If Not myRecipient.Resolved Then
         c.Add myRecipient
         TotalErrName = TotalErrName & sep & myRecipient.Name
         sep = ", "
     End If
Next myRecipient

For Each r In c
    r.Delete
Next r

MsgBox "The following names were not found in the address book " & _
        "and must be added manually: " & TotalErrName

答案 1 :(得分:0)

您正在修改正在处理的集合。使用下行循环:

For I = myRecipients.Count to 1 step -1
  set myRecipient = myRecipients.Item(I)
...