vbaoutlookruntime-error

Run-time error '424': Object Required - Outlook VBA


I have the following code in Outlook to save down attachments if an email is received that meets certain criteria. The code works, however I receive a Run-time error '424': Object Required anytime I startup Outlook. The debugger takes me to this line: Set objItems = objInbox.Items. But I'm not sure what the issue is or if its even an issue since the code seems to be working.

In addition, the VBA only works when I have my laptop on and Outlook running. How can I rewrite this code so that it works whether or not my computer is on and Outlook is running? These are emails being sent to a group email box, not just my personal email.

Public WithEvents objItems As Outlook.Items

Private Sub Application_Startup()
    Set objItems = objInbox.Items
End Sub

Private Sub objItems_ItemAdd(ByVal Item As Object)
    Dim objTaskRequest As Outlook.TaskRequestItem
End Sub


Sub BBDLPRICEMailMessageRule(MItem As Outlook.MailItem)
    Dim oAttachment As Outlook.Attachment
    Dim sSaveFolder As String
    Dim dateFormat As String

dateFormat = Format(Now, "yyyy-mm-dd_")
sSaveFolder = "N:\Applications\APX\Import\BB_DL_Prices"

For Each oAttachment In MItem.Attachments
    oAttachment.SaveAsFile sSaveFolder & "\" & oAttachment.DisplayName
Next
End Sub

Solution

  • You need to initialize the objInbox object in the code:

    Dim myNamespace As Outlook.NameSpace 
    
    Private Sub Application_Startup()
       Set myNamespace = Application.GetNamespace("MAPI")
       Set objInbox = myNamespace.GetDefaultFolder(olFolderInbox)  
       Set objItems = objInbox.Items
    End Sub