Use ItemChange event handler to update an item property

余生长醉 提交于 2020-01-25 10:32:05

问题


I have a list of contacts in Outlook updated through other program. I don't touch the list myself. Every time a contact is changed, I want to update company name through VBA.

Public WithEvents objNewContact As Items   
Public Sub Initialize_handler()
    Set objNewContact = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderContacts).Items
End Sub

Public Sub objNewContact_ItemChange(ByVal Item As Object)
    Item.CompanyName = "NewCompanyName"
    MsgBox "Company name changed to " & Item.CompanyName
End Sub

If I edit the contact myself through Outlook, it works. If edited through other source, it shows the MsgBox telling me that the company name has been changed, but the change is not saved.

If I add "Item.Save" it creates an infinite loop.

Public Sub objNewContact_ItemChange(ByVal Item As Object)
    Item.CompanyName = "NewCompanyName"
    MsgBox "Company name changed to " & Item.CompanyName
    Item.Save
End Sub

回答1:


You could toggle the ItemChange event handler off before changing Item.CompanyName.

Public Sub objNewContact_ItemChange(ByVal Item As Object)

    ' event handler off
    Set objNewContact = Nothing

    Item.CompanyName = "NewCompanyName"
    Item.Save

    MsgBox "Company name changed to " & Item.CompanyName

    ' event handler on
    Initialize_handler

End Sub



回答2:


You could wrap the inner behavior of your change method in a If statement. This way it will stop the infinite loop at the 2nd iteration as the Item won't be updated anymore :

Public Sub objNewContact_ItemChange(ByVal Item As Object)
    If Item.CompanyName != "NewCompanyName" Then
        Item.CompanyName = "NewCompanyName"
        MsgBox "Company name changed to " & Item.CompanyName
        Item.Save
    End If
End Sub


来源:https://stackoverflow.com/questions/56328031/use-itemchange-event-handler-to-update-an-item-property

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!