如何绕过使用Excel VBA答复邮件时生成错误的Outlook项目?

时间:2018-08-07 20:50:42

标签: excel vba excel-vba outlook

我有可以根据主题在用户Outlook中回复电子邮件的工作代码。如果最新的项目是会议邀请,我的代码将不会检索我想要的电子邮件。而是它将不通过会议邀请,并显示错误。

代码如下。

Sub Display()
Dim Fldr As Outlook.Folder
Dim olfolder As Outlook.MAPIFolder
Dim olMail As Outlook.MailItem
Dim olReply As Outlook.MailItem
Dim olItems As Outlook.Items
Dim i As Integer
Dim signature As String


Set Fldr = Session.GetDefaultFolder(olFolderInbox)
Set olItems = Fldr.Items
olItems.Sort "[Received]", True
For i = 1 To olItems.Count
    signature = Environ("appdata") & "\Microsoft\Signatures\"
    If Dir(signature, vbDirectory) <> vbNullString Then
        signature = signature & Dir$(signature & "*.htm")
    Else:
        signature = ""
    End If
    signature = CreateObject("Scripting.FileSystemObject").GetFile(signature).OpenAsTextStream(1, -2).ReadAll

    Set olMail = olItems(i)
    If InStr(olMail.Subject, Worksheets("Checklist Form").Range("B8")) <> 0 Then
        If Not olMail.Categories = "Executed" Then
            Set olReply = olMail.ReplyAll
            With olReply
             .HTMLBody = "<p style='font-family:calibri;font-size:14.5'>" & "Hi Everyone," & "<p style='font-family:calibri;font-size:14.5'>" & "Workflow ID:" & " " & Worksheets("Checklist Form").Range("B6") & "<p style='font-family:calibri;font-size:14.5'>" & Worksheets("Checklist Form").Range("B11") & "<p style='font-family:calibri;font-size:14.5'>" & "Regards," & "</p><br>" & signature & .HTMLBody

             .Display
             .Subject = "RO Finalized WF:" & Worksheets("Checklist Form").Range("B6") & " " & Worksheets("Checklist Form").Range("B2") & " -" & Worksheets("Fulfillment Checklist").Range("B3")
            End With

            Exit For
        olMail.Categories = "Executed"
        End If
    End If
Next i

End Sub

如果代码不会通过第一封电子邮件,是否可以绕过最近的项目。示例:会议邀请

1 个答案:

答案 0 :(得分:2)

Dim olMail As Outlook.MailItem
...
Set olMail = olItems(i)

Set分配不仅会在第一个项目是会议邀请时失败,还会对不是{{的任何olItems(i)(即i的任何值)失败1}}实例。其中包括可能会进入Outlook收件箱的所有内容,其中包括会议邀请。

一种可行的方法是处理Outlook.MailItem不是olItems(i)的特定情况下引发的运行时错误:

MailItem

请注意,我会尽早将赋值/验证放入循环中-这样一来,如果您不查看 For i = 1 To olItems.Count On Error GoTo ErrHandler ' jumps to error-handling subroutine if there's an error Set olMail = olItems(i) On Error GoTo 0 ' let any other error blow everything up ... SkipToNext: Next i Exit Sub ErrHandler: Debug.Print "Item index " & i & " is not a MailItem; skipping." Resume SkipToNext ,就不会运行无用的指令。


另一种更好的解决方法是验证MailItem的类型

olItems(i)

或者,您可以放弃跳Dim olItem As Object '... For i = 1 To olItems.Count Set olItem = olItems(i) If Not TypeOf olItem Is Outlook.MailItem Then Goto SkipToNext Set olMail = olItem ' essentially a type cast from Object to MailItem ... SkipToNext: Next 并增加嵌套级别:

GoTo

注意缩进;如果不确定如何正确且一致地执行此操作,请随时使用indenter。正确的缩进对于代码的可读性至关重要,尤其是考虑到嵌套循环和条件结构(免责声明:我拥有该网站以及该网站的OSS项目)。