0
votes
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 = "[email protected]" Then
                Set oMail = myitem.Forward
                oMail.Recipients.Add "[email protected]"
                oMail.HTMLBody = "Hi"
                oMail.Display
            End If
         End If
    End If
Next myitem

My code use to run properly a few weeks back. Today I ran again and debugging it I see that once it comes to Set oMail = myitem.Forward I get an outlook window open and an Run-time error saying Application-defined or object-defined error.

How can I get the forward email and error at the same time? First I use to get the outlook window only after the display command. Also due to this I am not able to execute the next lines of code in my forward email.

Edit:

Also now I see that directly displaying the email does not give any error, but once I use .Forward command this is when error comes.

1
what version of Outlook? there is an option to allow automation in the trust center settings.Sorceri

1 Answers

0
votes

Few Errors in your code, so I clean it up and added more code - Try it and let me know.

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 = "[email protected]" Then
                Set olItem = olItem.Forward
                    olItem.Recipients.Add "Om3r <[email protected]>"
                    olItem.HTMLBody = "Hi" + olItem.HTMLBody
                    olItem.Display
                End If
            End If
        End If
    Next
End Sub