如何使用VBA更新Outlook appoi?

时间:2016-10-24 12:33:48

标签: vba outlook outlook-vba outlook-2010

如何使用VBA更新/编辑现有日历约会?为什么以下VBA代码无法更新主题?

VBA sub:

Sub failToEditAppointment()
    Dim oSession  As Variant
    Set oSession = Application.Session
    Dim oCalendar As Variant
    Set oCalendar = oSession.GetDefaultFolder(olFolderCalendar)
    Dim oItems As Variant
    Set oItems = oCalendar.Items

    oItems.IncludeRecurrences = False
    oItems.Sort "[Location]"

    Debug.Print oItems(1).Subject
    oItems(1).Subject = "foo"
    Debug.Print oItems(1).Subject
    oItems(1).Save
    Debug.Print oItems(1).Subject
End Sub

输出:

  

情人节

     

情人节

     

情人节

2 个答案:

答案 0 :(得分:2)

您正在修改和保存不同的对象 - 每次调用oItems.Item(i)时,都会返回一个全新的COM对象,该对象无法保证知道该对象的其他实例。有时Outlook会缓存最后使用过的对象,有时则不会。将项目存储在专用变量中。更一般地说,多点符号(如oItem.Item(1))总是一个坏主意。

Dim oItem As Object

oItems.IncludeRecurrences = False
oItems.Sort "[Location]"
set oItem  = oItems(1)
Debug.Print oItem.Subject
oItem.Subject = "foo"
Debug.Print oItem.Subject
oItem.Save
Debug.Print oItem.Subject

答案 1 :(得分:0)

如果将项目设置为AppointmentItem类型的变量,则似乎有效。

Sub failToEditAppointment()
    Dim oSession  As Variant
    Set oSession = Application.Session
    Dim oCalendar As Variant
    Set oCalendar = oSession.GetDefaultFolder(olFolderCalendar)
    Dim oItems As Variant
    Set oItems = oCalendar.Items

    oItems.IncludeRecurrences = False
    oItems.Sort "[Location]"

    Dim appointment As AppointmentItem
    Set appointment = oItems(1)
    Debug.Print appointment.Subject
    appointment.Subject = "foo"
    Debug.Print appointment.Subject
    appointment.Save
    Debug.Print appointment.Subject
End Sub

<强>输出:

  

情人节

     

FOO

     

FOO