2016-04-21 97 views
0

要生成邮件列表,我已经认识到在我的变量“To”中包含相同的值[email protected]。邮件列表是在Visual Basic for Applications(VBA)中定义的。那么,我正在考虑如何定义一个语句来检查,当变量具有相同的值,然后修剪所有重复项。这意味着我需要变量在邮件列表中出现一次。变量包含相同的值(VBA)

例如:

Dim objMail As Object 
Dim objOutlook As Object 
Set objOutlook = CreateObject("Outlook.Application") 
Set objMail = objOutlook.CreateItem(0) 

With objMail 
    .To = [email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected] 
    ... 
End With 

有没有人有一个想法?

+0

什么数据类型是 “要” 变量?它是一个数组吗?或串联的字符串? – StormsEdge

+0

将列表转储到字典中。这确实是为了这样的事情。 –

+0

@StormsEdge我编辑了我的帖子。现在你可以看到变量是如何定义的。 – yuro

回答

2

你可以用字典来删除重复项:

Sub Test() 

    Dim EmailAddresses As String 

    EmailAddresses = "[email protected]; [email protected]; [email protected]; [email protected]; [email protected]; [email protected]" 
    EmailAddresses = RemoveDuplicates(EmailAddresses) 

    Debug.Print EmailAddresses 

End Sub 

Public Function RemoveDuplicates(sTo As String) As String 

    Dim dict As Object 
    Dim vEmails As Variant 
    Dim x As Long 
    Dim sTemp As String 

    vEmails = Split(Replace(sTo, " ", ""), ";") 
    If UBound(vEmails) > 0 Then 
     'Remove duplicates. 
     Set dict = CreateObject("Scripting.Dictionary") 
     For x = LBound(vEmails) To UBound(vEmails) 
      If Not dict.exists(vEmails(x)) Then 
       dict.Add vEmails(x), 1 
       sTemp = sTemp & vEmails(x) & ";" 
      End If 
     Next x 
     sTemp = Left(sTemp, Len(sTemp) - 1) 'Remove the final ; 
     RemoveDuplicates = sTemp 
    Else 
     'There's only 1 address. 
     RemoveDuplicates = sTo 
    End If 

End Function 

以上实际上可以简化一些方法也一样,如果这是你的偏好。

  1. 对于这样简单的去重,不需要使用。 Exists方法或.Add方法,因为字典项目是懒惰创建的。这意味着如果简单地引用一个项目,它将创建它,如果它不存在,或者覆盖它,如果它。
  2. 与字典并行手动构建字符串,您可以在字典的Keys上使用Join函数。

这里的修订版:

Public Function RemoveDuplicates2(sTo As String) As String 
    Dim dict As Object 
    Dim vEmails As Variant 
    Dim x As Long 

    vEmails = Split(Replace(sTo, " ", ""), ";") 
    Set dict = CreateObject("Scripting.Dictionary") 
    For x = LBound(vEmails) To UBound(vEmails) 
     dict(vEmails(x)) = dict(vEmails(x)) 'Keep track of how many occurrences, in case you want to do something with it later 
    Next 

    RemoveDuplicates = Join(dict.Keys(), "; ") 

End Function 
+0

好用的字典;我添加了一个稍微简化的方法(&解释)给你的答案,希望没关系:) –

+0

是的,这很好,谢谢@David。我只是自己开始使用字典,所以还是让我的头脑知道它是如何工作的。 –

+0

@ DarrenBartrup-Cook感谢Darren对你的帖子。我可以将你的例子与变量结合起来吗? – yuro