在VBA中区分不同的string和填充string?
我有两个string,我需要区分。 他们都有文字前后,我似乎无法弄清楚如何使它find每个string,并parsing出相关的信息。
Dim cell As Range Dim toPrimary As String Dim toCC As String For Each cell In Range("A2:A350") If cell.Value Like "*.USA.*" Then 'This is the first one toCC = toCC & ";" & "USA@email.com" ElseIf cell.Value Like "*.Burrito.*" Then toCC = toCC & ";" & "Durr@ito.com" ElseIf cell.Value Like "*.USA.Taco.*" Then 'This is the second toCC = toCC & ";" & "taco@bell.com" End If Next
我期待着.USA。 和.USA.Taco。 将用不同的信息填充toCC字段。 如果它有什么区别, .USA。 之后只有三个字符(即.USA.Pie。 ),而.USA.Taco。 在“美国”之后有同样的string“Taco”。
这是问题:
If cell.Value Like "*.USA.*" Then 'This is the first one '... '... '... ElseIf cell.Value Like "*.USA.Taco.*" Then 'This is the second '... End If
如果cell.Value
匹配*.USA.Taco.*
,那么它也匹配*.USA.*
,并给出了如何sorting的条件,如果任何匹配的*.USA.*
那么它并不重要匹配,因为一切都在ElseIf
块中。
翻转他们:validationcell.Value
匹配*.USA.Taco.*
之前 ,检查它是否匹配*.USA.*
:
If cell.Value Like "*.USA.Taco.*" Then '... ElseIf cell.Value Like "*.USA.*" Then '... ElseIf cell.Value Like "*.Burrito.*" Then '... End If
你只想列出每个收件人一次 – 没有人想要收到300次相同的电子邮件(假设他们的邮件服务器不只是阻止发件人)。
而不是像这样build立一个string,做一个键控集合:
Dim ccRecipients As Collection Set ccRecipients = New Collection If cell.Value Like ... ccRecipients.Add "USA@email.com", Key:="USA@email.com" ElseIf cell.Value Like ... ccRecipients.Add "Durr@ito.com", Key:="Durr@ito.com" ...
当将重复地址添加到集合时,这将引发错误。 所以请做一个专门的程序来安全地执行它:
Private Sub AddUniqueItemToCollection(ByVal value As String, ByVal items As Collection) On Error Resume Next items.Add value, key:=value On Error GoTo 0 End Sub
然后调用它:
Dim ccRecipients As Collection Set ccRecipients = New Collection If cell.Value Like ... AddUniqueItemToCollection "USA@email.com", ccRecipients ElseIf cell.Value Like ... AddUniqueItemToCollection "Durr@ito.com", ccRecipients ...
然后,您可以迭代集合中的唯一项目,将它们添加到数组中:
ReDim ccAddresses(0 To ccRecipients.Count - 1) Dim ccAddress As Variant, ccItem As Long For Each ccAddress In ccRecipients ccAddresses(ccItem) = CStr(ccAddress) ccItem = ccItem + 1 Next
现在,您可以使用Join
来构build收件人的最终列表,并用分号分隔每个收件人:
Dim sendToCC As String sendToCC = Join(ccAddresses, ";")
这样你就不会发送垃圾邮件给任何人的收件箱!