2016-04-21 82 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