由于运行时错误导致无法转发电子邮件' 

时间:2015-12-21 19:47:34

标签: vba outlook outlook-vba

Set myNameSpace = myOlApp.GetNamespace("MAPI")
Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
Set myitems = myInbox.Items

For Each myitem In myitems
    If myitem.Class = olMail Then
        If InStr(1, myitem.Subject, "Greetings") > 0 Then
            senderemail = myitem.Sender.GetExchangeUser.PrimarySmtpAddress
            If senderemail = "abc@xyz.com" Then
                Set oMail = myitem.Forward
                oMail.Recipients.Add "i@me.com"
                oMail.HTMLBody = "Hi"
                oMail.Display
            End If
         End If
    End If
Next myitem

我的代码用于在几周前正常运行。今天我再次运行并调试它我看到,一旦涉及到设置oMail = myitem.Forward 我打开了一个Outlook窗口,并显示一个运行时错误,说明了应用程序定义或对象定义的错误。

如何同时收到转发电子邮件和错误消息?首先,我只使用display命令后才能获取outlook窗口。同样由于这个原因,我无法在我的转发电子邮件中执行下一行代码。

修改:

此外,我现在看到直接显示电子邮件不会出现任何错误,但是一旦我使用 .Forward 命令,就会出现错误。

1 个答案:

答案 0 :(得分:0)

您的代码中存在少量错误,因此我将其清理并添加更多代码 - 试试并告知我们。

Option Explicit
Sub olForward()
    Dim olApp As Outlook.Application
    Dim olFolder As Outlook.MAPIFolder
    Dim olInbox As Outlook.MAPIFolder
    Dim olNameSpace As Outlook.NameSpace
    Dim olItem As Outlook.MailItem
    Dim olSender As String

    Set olApp = New Outlook.Application
    Set olNameSpace = Application.GetNamespace("MAPI")
    Set olInbox = olNameSpace.GetDefaultFolder(olFolderInbox)

    '// Require this procedure be called only when a message is selected
    If Application.ActiveExplorer.Selection.Count = 0 Then
        Exit Sub
    End If

    For Each olItem In Application.ActiveExplorer.Selection
        If olItem.class = olMail Then
            If InStr(1, olItem.Subject, "Greetings") > 0 Then
            olSender = olItem.SenderEmailAddress
                If olSender = "abc@xyz.com" Then
                Set olItem = olItem.Forward
                    olItem.Recipients.Add "Om3r <i@me.com>"
                    olItem.HTMLBody = "Hi" + olItem.HTMLBody
                    olItem.Display
                End If
            End If
        End If
    Next
End Sub