user2672288
user2672288

Reputation:

outlook vba - move email to folder, object required

I'm trying to write some vba which will move emails as they are received into a certain folder.

The code, so far, is:

Private WithEvents myItems as Outlook.Items
Public Sub Application_Startup()
    Dim myApp as Outlook.Application
    Dim myNameSpace as Outlook.NameSpace
    Dim myInbox as Outlook.Folder

    Set myApp = Outlook.Application
    Set myNameSpace = myApp.GetNamespace("MAPI")
    Set myInbox = myNameSpace.GetDefaultFolder(olFolderInbox)
    Set myItems = myInbox.Items
End Sub

Private Sub myItems_ItemAdd(ByVal item as Object)
    Dim msg as Outlook.MailItem
    Dim recips as String
    Dim destFolder as Outlook.Folder

    Set destFolder = myInbox.Folders("Test")
    Set msg = item
    recips = msg.To
    If InStr(recips, "m0atz") Then
          msg.Move destFolder
    End If

    Set msg = nothing
    Set destFolder = nothing
End Sub

The issue I'm having is an error when an email is received from this line:

Set destFolder = myInbox.Folders("Test")

saying "run-time error 424 - Object Required"

Any ideas greatly appreciated.

Upvotes: 2

Views: 900

Answers (1)

Heinzi
Heinzi

Reputation: 172418

myInbox is a local variable of Application_Startup. Thus, it's only accessible in Application_Startup.

I strongly recommend to add Option Explicit On to the top of your module. This will alert you of such errors (and others).

To solve your problem, either

  • discover myInbox again in your myItems_ItemAdd method (you might want to extract your Application_Startup code into a method for that) or

  • declare myInbox outside your method (just like myItems) to make it globally accessible. Note that such "global variables" should be used sparingly and only if really necessary.

Upvotes: 1

Related Questions