为什么outlook约会偶尔不会被删除

Why does an outlook appointment not get deleted occasionally

我在 Excel 工作簿中有一个 VBA 宏,它在用户日历中创建带有特殊标记的 Outlook 约会。在添加新约会之前,它首先删除项目正文中具有此标签的所有约会。不幸的是,Outlook.AppointmentItem.Delete 功能有时不起作用。当我打开 Outlook 日历时,我可以看到该项目在很短的时间内被删除并立即重新出现。这种情况只是偶尔发生。

我可以通过将具有特定标记的 AppointmentItem 复制两次来强制执行该行为。然后,只有两个约会将被删除,一个保留在日历中。

任何人都可以解释可能导致此行为的原因吗?

Public Sub DeleteAppointment(Starttime As Date, Endtime As Date)

    Dim myStart As Date
    Dim myEnd As Date
    Dim olApp As Outlook.Application
    Dim oCalendar As Outlook.Folder
    Dim oItems As Outlook.Items
    Dim oItemsInDateRange As Outlook.Items
    Dim oAppt As Outlook.AppointmentItem
    Dim strRestriction As String
    Dim olNs As Outlook.Namespace
    Dim blnCreated As Boolean

    On Error Resume Next
    Set olApp = Outlook.Application

    If olApp Is Nothing Then
        Set olApp = Outlook.Application
        blnCreated = True
        Err.Clear
    Else
        blnCreated = False
    End If

    On Error GoTo 0

    myStart = Starttime
    myEnd = DateAdd("h", 24, Starttime)

    'MsgBox ("Searching from " & Format(myStart, "mm.dd.yyyy hh:mm") & " to " & Format(myEnd, "mm.dd.yyyy hh:mm"))

    'Construct filter for the range
    strRestriction = "[Start] <= '" & myEnd & "' AND [End] >= '" & myStart & "'"

    ' Set Outlook Objects
    Set olNs = olApp.GetNamespace("MAPI")
    Set oCalendar = olNs.GetDefaultFolder(olFolderCalendar)
    Set oItems = oCalendar.Items

    oItems.IncludeRecurrences = True
    oItems.Sort "[Start]"
    'Restrict the Items collection for the range
    Set oItemsInDateRange = oItems.Restrict(strRestriction)
    oItemsInDateRange.Sort "[Start]"

    For Each oAppt In oItemsInDateRange
        'MsgBox ("Found item " & oAppt.Subject & " from " & oAppt.Start & " to " & oAppt.End)
        If (InStr(oAppt.Body, OutlookTag) <> 0) Then
            'MsgBox ("Found an appointment that I generated. Going to delete it." & oAppt.Subject)
            oAppt.Delete
            Set oAppt = Nothing
        End If
    Next
End Sub

扩展 Tim William 的评论:

想象一个包含项目 (1) "foo" 和 (2) "bar" 的数组。您迭代 "For each item in foobar()"。它查看第 1 项并将其删除。然后移动整个集合。项目 (1) 变为 "bar",并且没有更多的项目 2。您的循环继续,并查看下一个项目 - 但因为列表中现在只有 1 个项目,并且它刚刚循环过项目1,任务完成。

解决方案:更改循环,从 2 向下移动到 1。除非您不能使用 VBA 中的 "For Each x in y" 命令执行此操作。

相反,正如@TimWilliams 所建议的那样,遍历集合,将 id 添加到要删除的新集合,然后删除整个 'to delete' 集合。