拆分收件人姓名以获取名字

时间:2017-09-19 20:56:42

标签: vba outlook

我试图打破两个收件人的全名来获得名字。

以下是代码:

For r = 1 To .recipients.Count
    Debug.Print .recipients(r)
    strgreetname = Left(.recipients(r), InStr(1, .recipients(r), " ") - 1)
    strTo = Left(strGreetNameAll, InStr(1, .recipients(r), " ") - 2)
    strGreetNameAll = strGreetNameAll & strgreetname & ", "
    strgreetnameall1 = strgreetname
Next r

For i = 1 To .recipients.Count
    Debug.Print .recipients(i)
    strgreetname = Left(.recipients(i), InStr(1, .recipients(i), " ") - 1)
    strTo1 = Right(strTo, InStr(1, .recipients(i), " ") - 2)
    strGreetNameAll = strGreetNameAll & strgreetname & ", "
    strgreetnameall1 = strgreetname
Next i

根据收件人数量,我无法让strTostrTo1单独工作。它似乎只有在我更改第一个定义的项目时才会改变,在本例中为r。更改i值不起作用。似乎第一个定义的变量控制着它下面的所有内容,即使我将它单独设置。如何解决这些问题,以便r控制一个部分,而i控制另一个部分,以便它们自主工作?

更新 - 我把它分开但是第一个别名(strTO)以奇怪的方式切断了。我想在别名的第一个空格处切断,我以为我用“左”的一块做了。但是,如果第一个别名是短名称(如Tom),则不一致,切断长名称,或者拉入下一个名称的部分内容。

For R = 1 To .recipients.Count
    Debug.Print .recipients(R)
    strgreetname = Left(.recipients(R), InStr(1, .recipients(R), " "))
    strgreetname2 = Left(.recipients(2), InStr(1, .recipients(R), " "))
    strGreetNameAll = strGreetNameAll & strgreetname
    strGreetNameAll1 = strgreetname
    strTo = Left(strGreetNameAll, InStr(1, .recipients(R), " "))
    strTo1 = Left(strgreetname2, InStr(1, .recipients(R), " "))
Next R

StrTO和strTO1分别是To字段中的第一个和第二个别名。

例如: 鉴于。收件人“William Hartnell”,“Carole Ann Ford”,“Patrick Troughton”,“Anneke Wills”,“Jon Pertwee”和“Tom Baker”。

我希望strTO成为威廉。我希望strTO1成为Carole。所以它可能是亲爱的威廉和卡罗尔。

2 个答案:

答案 0 :(得分:0)

你这样做

for r = 1 to 10
    a = r + 4
next r

for i = 1 to 10
    b = a + 2
next r

何时需要

for r = 1 to 10
    a = r + 4
    b = a + 2
next r

答案 1 :(得分:0)

根据您的评论,您希望strTO成为.Recipients(1)中第一个空格的所有字符,并且您希望strTO1成为.Recipients(2)中第一个空格的所有字符{1}},然后您可以使用以下代码:

strTO = Left(.Recipients(1), InStr(.Recipients(1) & " ", " ") - 1)
If .Recipients.Count > 1 Then
    strTO1 = Left(.Recipients(2), InStr(.Recipients(2) & " ", " ") - 1)
Else
    strTO1 = ""
End If

而且,如果您使用它来创建"问候",您可以使用以下内容:

strGreetName = Left(.Recipients(1), InStr(.Recipients(1) & " ", " ") - 1)

If .Recipients.Count > 1 Then
    strGreetName = strGreetName & " and " & Left(.Recipients(2), InStr(.Recipients(2) & " ", " ") - 1)
End If

并且不用担心strTOstrTO1

或者,如果您想要包含所有名称,可以使用类似

的内容
strGreetName = ""
For i = 1 to .Recipients.Count
    If i > 1 Then
        If i = .Recipients.Count Then
            strGreetName = strGreetName & " and "
        Else
            strGreetName = strGreetName & ", "
        End If
    End If
    strGreetName = strGreetName & Left(.Recipients(i), InStr(.Recipients(i) & " ", " ") - 1)
Next