检查AddMember方法是否失败

时间:2019-02-21 16:41:32

标签: excel vba outlook

我正在用VBA(在Excel中)编写代码,将Outlook联系人放入通讯组列表中。

到目前为止,该方法仍然有效,但是如果该联系人不存在,则无法进行错误处理。 MS说

  

如果指定的收件人无效,则AddMember方法将   失败。

那么您如何注意到该方法是否失败?

6

我尝试过

Public Function olAddContactToList(ByVal sLastName As String, _
  Optional ByVal sFirstName As String, _
  Optional ByVal sGroup As String) As Boolean

  Dim oOutlook As Object    ' Outlook.Application
  Dim oNameSpace As Object  ' Outlook.NameSpace
  Dim oMAPIFolder As Object ' Outlook.MAPIFolder
  Dim oContact As Object    ' Outlook.ContactItem
  Dim oList As Object       ' Outlook.DistListItem
  Dim oMail As Object       ' Outlook.MailItem
  Dim oRecip As Object      ' Outlook.Recipient

  Const olFolderContacts = 10

  On Error GoTo ErrHandler

  Set oOutlook = CreateObject("Outlook.Application")
  Set oNameSpace = oOutlook.GetNamespace("MAPI")
  Set oMAPIFolder = oNameSpace.GetDefaultFolder(olFolderContacts)
  Set oList = oNameSpace.GetDefaultFolder(olFolderContacts).Items(sGroup)

 'Adds a member to a new distribution list
 Set oMail = oOutlook.CreateItem(olMailItem)

 'Create recipient for distlist
 Set oRecip = oOutlook.Session.CreateRecipient(sFirstName & " " & sLastName)

 oRecip.Resolve

 oList.AddMember oRecip

 oList.Save
 olAddContactToList = True

ErrHandler:
  If Err.Number <> 0 Then
    MsgBox "Fehler beim Hinzufügen des Outlook-Kontakts zu einer Liste." & vbCrLf & _
      CStr(Err.Number) & " " & Err.Description, vbExclamation + vbOKOnly

    olAddContactToList = False
  End If

  Set oContact = Nothing
  Set oMAPIFolder = Nothing
  Set oNameSpace = Nothing
  Set oOutlook = Nothing
  Set oList = Nothing
  Set oMail = Nothing
  Set oRecip = Nothing

End Function

但是Dim AddCheck As Long AddCheck = oList.AddMember(oRecip) 保持为0,无论该联系人是否存在且已成功添加到列表中,或者联系人是否不存在并未能添加。

1 个答案:

答案 0 :(得分:1)

由于Recipient.Resolve的结果是TrueFalse(例如Microsoft),因此应进行检查。
否则,您只有名字和姓氏,而没有完整的电子邮件地址:

If Not oRecip.Resolve Then
    ' no resulting email address
Else
    ' email address found, go further
End If

由于DistListItem.AddMember不会引起任何错误,如果您尝试添加简单的电话号码字符串(只是不添加它),我建议比较DistListItem.MemberCount(代码中的oList.MemberCount)尝试添加新成员之前和之后。

如果出现问题,您将得到一个错误或一个不变的成员数,并且可以进行进一步的检查。