0

I'm trying to modify incoming emails in a specific folder and send it to another person.

The part modify/send works.

The script doesn't work when there is new email. It only works when I transfer it to myself.

The beginning of the code:

Private WithEvents Items As Outlook.Items
Private Sub Application_Startup()
    Dim olApp As Outlook.Application
    Dim objNS As Outlook.NameSpace
    Set olApp = Outlook.Application
    Set objNS = olApp.GetNamespace("MAPI")
    ' default local Inbox
    Set Items = objNS.GetDefaultFolder(olFolderInbox).Folders("DI").Items
End Sub

Private Sub Items_ItemAdd(ByVal item As Object)
    Dim Msg As Outlook.MailItem
    If TypeName(item) = "MailItem" Then
        Set Msg = item
Community
  • 1
  • 1
Lispeenium
  • 59
  • 8

1 Answers1

0

Did you restart your Outlook? Please refer to the following code:

Private WithEvents Items As Outlook.Items

Private Sub Application_Startup()
  Dim olApp As Outlook.Application

  Set olApp = Outlook.Application
  Set Items = GetNS(olApp).GetDefaultFolder(olFolderInbox).Folders("Stuff").Items
End Sub

Private Sub Items_ItemAdd(ByVal item As Object)

  On Error GoTo ErrorHandler

  MsgBox "You moved an item into the 'Stuff' folder."

ProgramExit:
  Exit Sub
ErrorHandler:
  MsgBox Err.Number & " - " & Err.Description
  Resume ProgramExit
End Sub

Function GetNS(ByRef app As Outlook.Application) As Outlook.NameSpace
  Set GetNS = app.GetNamespace("MAPI")
End Function

Here is a link: VBA Outlook event moving email

Simon Li
  • 303
  • 2
  • 4
  • Thank You, when I restart outlook, it seems to work. I don't understand this part of the code you gave. Why is it in a function ? Function GetNS(ByRef app As Outlook.Application) As Outlook.NameSpace Set GetNS = app.GetNamespace("MAPI") End Function – Lispeenium Sep 25 '18 at 13:50
  • I think it should be convenient to make multiple calls and improve code efficiency. You can see the following link:https://www.mrexcel.com/forum/excel-questions/801900-retrieving-outlook-contact-details-using-vba.html – Simon Li Sep 25 '18 at 15:14
  • 1
    Could you please mark the answer and close the post if it helps. – Simon Li Sep 25 '18 at 23:56