你可以用字典來刪除重複項:
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
以上實際上可以簡化一些方法也一樣,如果這是你的偏好。
- 對於這樣簡單的去重,不需要使用。
Exists
方法或.Add
方法,因爲字典項目是懶惰創建的。這意味着如果簡單地引用一個項目,它將創建它,如果它不存在,或者覆蓋它,如果它。
- 與字典並行手動構建字符串,您可以在字典的
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
什麼數據類型是 「要」 變量?它是一個數組嗎?或串聯的字符串? – StormsEdge
將列表轉儲到字典中。這確實是爲了這樣的事情。 –
@StormsEdge我編輯了我的帖子。現在你可以看到變量是如何定義的。 – yuro