Sub SaveAttachmentsAsZip()
Dim m As MailItem, myInspector As Inspector, myAttachment As Attachment
Dim ZipFileName As Variant, FolderName As Variant, ZipFile As Variant
Dim oApp As Object, myAttachments() As String, i As Integer, j As Integer
Dim watchdog As Integer, t As Date, ZipCount As Integer
'Change these 2 variables to reflect where and what you want to save/name the zip file
[COLOR=#ff0000]FolderName [/COLOR]= "C:\Users\Username\Documents\ExcelTesting\"
[COLOR=#ff0000]ZipFileName [/COLOR]= "test.zip"
Set myInspector = ActiveInspector
If Not myInspector Is Nothing Then
If TypeName(myInspector.CurrentItem) = "MailItem" Then
Set m = myInspector.CurrentItem
i = -1
For Each myAttachment In m.Attachments
If InStr(1, m.HTMLBody, "cid:" & myAttachment.FileName) < 1 Then
myAttachment.SaveAsFile (FolderName & myAttachment.FileName)
i = i + 1
ReDim Preserve myAttachments(i)
myAttachments(i) = myAttachment.FileName
End If
Next myAttachment
If i > -1 Then
ZipFile = FolderName & ZipFileName
If NewZip(ZipFile) = True Then
Set oApp = CreateObject("Shell.Application")
ZipCount = 1
For j = 0 To i
watchdog = 0
oApp.NameSpace(ZipFile).CopyHere FolderName & myAttachments(j)
'Keep script waiting until Compressing is done
On Error Resume Next
Do Until oApp.NameSpace(ZipFile).Items.Count = ZipCount Or watchdog > 20
watchdog = watchdog + 1
t = Now + TimeValue("00:00:01")
Do Until Now - t > 0
If oApp.NameSpace(ZipFile).Items.Count = ZipCount Then Exit Do
DoEvents
Loop
Loop
On Error GoTo 0
If watchdog > 20 Then
If MsgBox("There was an error adding " & myAttachments(i) & _
" to the zip file. Continue?", vbYesNo, "Zip Error") = vbNo Then
Exit For
End If
Else
ZipCount = ZipCount + 1
Kill FolderName & myAttachments(j)
End If
Next j
If ZipCount = i + 2 Then
MsgBox "Zip complete."
Else
MsgBox "Done with some errors."
End If
Else
MsgBox ("Move or rename " & ZipFileName & " before trying again.")
End If
Else
MsgBox ("No attachments to save.")
End If
End If
End If
Set m = Nothing
Set myInspector = Nothing
Set oApp = Nothing
End Sub
Function NewZip(sPath) As Boolean
If Len(Dir(sPath)) > 0 Then
If MsgBox(sPath & " already exists. Delete it and continue?", vbYesNo, "Zip Error") = vbYes Then
Kill sPath
Else
NewZip = False
Exit Function
End If
End If
NewZip = True
Open sPath For Output As [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL]
Print [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL] , Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close [URL=https://www.mrexcel.com/forum/usertag.php?do=list&action=hash&hash=1]#1[/URL]
End Function