0

I am trying to auto forward an email from a specific sender and with a specific subject to a list of new recipients.

When I create a Run a Script Rule, my script is not shown.

  1. Add my script via VBA Editor
  2. Rules > Manage Rules & Alerts > Run a script
  3. Select Run a script action -> Can not Select my script (script not show)
Option Explicit
 
Public WithEvents objInbox As Outlook.Folder
Public WithEvents objInboxItems As Outlook.Items
 
Private Sub Application_Startup()
    Set objInbox = Outlook.Application.Session.GetDefaultFolder(olFolderInbox)
    Set objInboxItems = objInbox.Items
End Sub
 
Private Sub objInboxItems_ItemAdd(ByVal Item As Object)
    Dim objMail As Outlook.MailItem
    Dim objForward As Outlook.MailItem
 
    Dim xStr1 As String
    Dim xStr2 As String
 
    If TypeOf Item Is MailItem Then
        Set objMail = Item
 
        If (objMail.SenderEmailAddress = "T@com") And (objMail.Subject = "ZZZZZ") Then
            Set objForward = objMail.Forward
            GoTo commonOutput
        End If
 
    End If
    Exit Sub
 
commonOutput:
    With objForward
        .HTMLBody = xStr1 & xStr2 & Item.HTMLBody
        .Display
    End With
 
Release:
    Set myFwd = Nothing
 
End Sub
Ehvince
  • 17,274
  • 7
  • 58
  • 79
TS Pham
  • 21
  • 4
  • `objInboxItems_ItemAdd` should run automatically when an item is added to the inbox. Open an item you think should trigger ItemAdd code to test the logic. https://stackoverflow.com/a/58049467/1571407 – niton Mar 22 '22 at 20:44
  • Run a script is usually disabled. You could search for how to reenable but it is not applicable here. – niton Mar 22 '22 at 21:00

1 Answers1

0

VBA script which can be assigned to a rule should have the following signature:

Public Sub Test(item as object)
  ' your code 
End Sub

Your existing code does almost the same without rules. It handles the ItemAdd event for the Inbox folder, so you just need to replace the Display method call with Send:

Private Sub objInboxItems_ItemAdd(ByVal Item As Object)
    Dim objMail As Outlook.MailItem
    Dim objForward As Outlook.MailItem

    Dim xStr1 As String
    Dim xStr2 As String

    If TypeOf Item Is MailItem Then
        Set objMail = Item

        If (objMail.SenderEmailAddress = "T@com") And (objMail.Subject = "ZZZZZ") Then
            Set objForward = objMail.Forward
            GoTo commonOutput
        End If

    End If
    Exit Sub

   commonOutput:
    With objForward
        .HTMLBody = xStr1 & xStr2 & Item.HTMLBody
        .Send
    End With

Release:
    Set myFwd = Nothing

End Sub
Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45