I am trying to modify this VBA code to save all attachments from emails in an Inbox subfolder
. Items populates with all the messages in this folder but the rest of the code is not working.
I am trying to print out the item object to debug and that isn't working either.
Original code: https://community.spiceworks.com/scripts/show/361-auto-save-attachments-to-folder
Update 1: I realized now only Application_Startup() can be debugged by using the Run button. Sending a test email I was able to step through the program and see everything is working as expected.
Option Explicit
Public WithEvents Items As Outlook.Items
Public Sub Application_Startup()
Dim olNs As Outlook.NameSpace
Set olNs = Application.GetNamespace("MAPI")
Dim Inbox As Outlook.MAPIFolder
Set Inbox = olNs.GetDefaultFolder(olFolderInbox)
Dim Sub_folder As Outlook.MAPIFolder
Set Sub_folder = Inbox.Folders("DocuSign")
Set Items = Sub_folder.Items
End Sub
Public Sub Items_ItemAdd(ByVal Item As Object)
Stop
If TypeOf Item Is Outlook.MailItem Then
Debug.Print Item.Subject
End If
On Error GoTo ErrorHandler
'Only act if it's a MailItem
Dim Msg As Outlook.MailItem
If TypeName(Item) = "MailItem" Then
Set Msg = Item
'Change variables to match need. Comment or delete any part unnecessary.
If (Msg.SenderEmailAddress = "test@email.com") And _
(InStr(Msg.Subject, "Completed:")) And _
(Msg.Attachments.Count >= 1) Then
'Set folder to save in.
Dim olDestFldr As Outlook.MAPIFolder
Dim myAttachments As Outlook.Attachments
Dim Att As String
'location to save in. Can be root drive or mapped network drive.
Const attPath As String = "C:\Users\Austin\Desktop\temp\"
' save attachment
Set myAttachments = Item.Attachments
Att = myAttachments.Item(1).DisplayName
' remove .pdf
Att = Left(Att, InStrRev(Att, ".") - 1)
myAttachments.Item(1).SaveAsFile attPath & Att & "_signed.pdf"
' mark as read
Msg.UnRead = False
End If
End If
ProgramExit:
Exit Sub
ErrorHandler:
MsgBox Err.Number & " - " & Err.Description
Resume ProgramExit
End Sub