The following code forwards email I move to specific subfolders of the 'Outsourced Accounting' folder.
I would like to forward email moved to any subfolder of 'OutsourcedAccounting' without having to update the code any time a new subfolder is added.
How can I make this work for any subfolder of OutsourcedAccounting as opposed to just those I specifically name in the code?
Option Explicit
Private WithEvents OutsourcedAccounting As Outlook.Items
Private WithEvents Subfolder1 As Outlook.Items
Private WithEvents subfolder2 As Outlook.Items
Private WithEvents Subfolder3 As Outlook.Items
Private olItem As Outlook.MailItem
Private Sub Application_Startup()
Dim olApp As Outlook.Application
Set olApp = Outlook.Application
Set OutsourcedAccounting = GetNS(olApp).GetDefaultFolder(olFolderInbox).Folders("Outsourced Accounting").Items
Set Subfolder1 = GetNS(olApp).GetDefaultFolder(olFolderInbox).Folders("Outsourced Accounting").Folders("Subfolder1").Items
Set subfolder2 = GetNS(olApp).GetDefaultFolder(olFolderInbox).Folders("Outsourced Accounting").Folders("subfolder2").Items
Set Subfolder3 = GetNS(olApp).GetDefaultFolder(olFolderInbox).Folders("Outsourced Accounting").Folders("Subfolder3").Items
lbl_Exit:
Exit Sub
End Sub
Private Sub OutsourcedAccounting_ItemAdd(ByVal item As Object)
On Error GoTo err_Handler
Set olItem = item.Forward
olItem.Recipients.Add "forwardingemail@gmail.com"
olItem.Save
olItem.Send
lbl_Exit:
Exit Sub
err_Handler:
MsgBox Err.Number & " - " & Err.Description
GoTo lbl_Exit
End Sub
Private Sub Subfolder1_ItemAdd(ByVal item As Object)
On Error GoTo err_Handler
Set olItem = item.Forward
olItem.Recipients.Add "forwardingemail@gmail.com"
olItem.Save
olItem.Send
lbl_Exit:
Exit Sub
err_Handler:
MsgBox Err.Number & " - " & Err.Description
GoTo lbl_Exit
End Sub
Private Sub subfolder2_ItemAdd(ByVal item As Object)
On Error GoTo err_Handler
Set olItem = item.Forward
olItem.Recipients.Add "forwardingemail@gmail.com"
olItem.Save
olItem.Send
lbl_Exit:
Exit Sub
err_Handler:
MsgBox Err.Number & " - " & Err.Description
GoTo lbl_Exit
End Sub
Private Sub Subfolder3_ItemAdd(ByVal item As Object)
On Error GoTo err_Handler
Set olItem = item.Forward
olItem.Recipients.Add "forwardingemail@gmail.com"
olItem.Save
olItem.Send
lbl_Exit:
Exit Sub
err_Handler:
MsgBox Err.Number & " - " & Err.Description
GoTo lbl_Exit
End Sub
Function GetNS(ByRef app As Outlook.Application) As Outlook.NameSpace
Set GetNS = app.GetNamespace("MAPI")
lbl_Exit:
Exit Function
End Function