0

I put this in a rule to automate saving a zipped file I get in emails throughout the day:

Public Sub SaveZip(itm As Outlook.MailItem)

    Const saveFolder = "C:\Users\Example\Example\Example\"

    Dim objAtt As Outlook.Attachment
    Dim oApp As Object
    Dim dName As Variant, unZipFolder

    If itm.Attachments.Count > 0 Then

        unZipFolder = saveFolder & "unzipped\"

        MkDir unZipFolder 

        For Each objAtt In itm.Attachments

            dName = objAtt.DisplayName

            objAtt.SaveAsFile saveFolder & dName

            Set oApp = CreateObject("Shell.Application")

            oApp.NameSpace(unZipFolder).CopyHere _
              oApp.NameSpace(saveFolder & dName).Items

        Next
    End If     'any attachments
End Sub

It works once then won't work for following emails. Nothing happens after the first file is saved and unzipped.

Community
  • 1
  • 1
IzziB
  • 1
  • 1
  • [Edit](https://stackoverflow.com/posts/71180518/edit) the question to put in the error message or other result if any. – niton Feb 18 '22 at 23:31
  • Nothing happens after the first file is saved and unzipped – IzziB Feb 18 '22 at 23:45
  • Either delete `MkDir unZipFolder` or check if existing first [Create folder path if does not exist](https://stackoverflow.com/questions/43658276/create-folder-path-if-does-not-exist-saving-from-vba). A simple, but frowned upon, way https://stackoverflow.com/a/63341029/1571407. – niton Feb 19 '22 at 00:15

1 Answers1

0

You need to run your code under the debugger to understand why it fails. Try to set a break point in the code and see which line of code gives an error message.

Also I'd suggest declaring the parameter as object in the function because incoming items can be different - appointments, mails, non-delivery reports and etc.:

itm As Outlook.MailItem

You may consider handling the NewMailEx event of the Application class instead of having a function called by the rule assigned. The NewMailEx event fires when a new message arrives in the Inbox and before client rule processing occurs. The item can be one of several different item types, for example, MailItem, MeetingItem, or SharingItem. Use the Entry ID represented by the EntryIDCollection string to call the NameSpace.GetItemFromID method and process the item.

Also I'd suggest adding On Error statements to the code so you could handle errors correctly. You may consider using the On Error Resume Next which specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred and execution continues. Use this form rather than On Error GoTo when accessing objects.

Eugene Astafiev
  • 47,483
  • 3
  • 24
  • 45