问题
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