vba to secure zip attachments

Post number 3 has been selected as the best answer.

Status
Not open for further replies.

shrydvd

New Member
Outlook version
Outlook 2019 64-bit
Email Account
IMAP
I am hoping someone can pull me out of this . . . I am trying to identify emails that have attachments then zip those attachments together with a password. I end up with different errors but can't seem to get it. One of the main errors is with PKZip in the command line saying "Nothing to do". I am sure it has something to do with how I am trying to tell it which files to zip.

Anyway, here is what I have. It is a mixed bag of pieces I have gotten elsewhere and trying to put them together.

If I am way off base and need to scrap it & start over, please tell me that as well. Also, there is likely extraneous junk in the code below simply because I keep trying different things.

Thank you for any guidance you can provide.
Code:
Sub ZipdAttach()

    Dim objMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objAttachment As Outlook.Attachment
    Dim objFileSystem As Object
    Dim objShell As Object
    Dim varTempFolder As Variant
    Dim varZipFile As Variant
    Dim myDir As String
    Dim dest As Variant
    Dim srce As Variant
    Dim strCommand As String
    Dim val As String
    'Save the attachments to Temporary folder
    Set objFileSystem = CreateObject("Scripting.FileSystemObject")
    varTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp " & Format(Now, "dd-mm-yyyy- hh-mm-ss-")
    MkDir (varTempFolder)
    varTempFolder = varTempFolder & "\"
 
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    Set objAttachments = objMail.Attachments
    For Each objAttachment In objAttachments
        objAttachment.SaveAsFile (varTempFolder & objAttachment.FileName)
    Next
 
   'Create a new zip file
    varZipFile = InputBox("Specify a name for the new zip file", "Name Zip File", objMail.Subject)
    varZipFile = varTempFolder & varZipFile
 
    'Copy all the saved attachments to the new zip file
     Set objShell = CreateObject("Shell.Application")
    
'_______________________________________________


val = InputBox("Give me an 8 character password.")
myDir = "C:\Program Files\PKWARE\PKZIPC"
dest = varZipFile
srce = varTempFolder
strCommand = "pkzipc.exe -add -passphrase=" & val & " " & dest & " " & srce
Call Shell("cmd.exe /k cd /d " & myDir & " & " & strCommand, 1)

End Sub
 
>> Also, there is likely extraneous junk in the code below simply because I keep trying different things.
LOL. A lot of my code has unnecessary junk in it for the same reason.

Try this change:
srce = varTempFolder & *.*

From the way i read the documentation, it should add the folder contents when you use just the folder, but designating all files in the folder works here.
 
Last edited:
I'm sorry I didn't get back with you to say thank you. When I tried your answer, it worked great & I got carried away with the rest of the project. Anyway, while I am sure my code is "less than elegant" to say the least, this works for me if it will help someone else.
Thank you again to Diane for her guidance that made it all finally work!


Code:
Sub ZipAttach()
    Dim objMail As Outlook.MailItem
    Dim objAttachments As Outlook.Attachments
    Dim objAttachment As Outlook.attachment
    Dim objFileSystem As Object
    Dim varTempFolder As String
    Dim varzipfile As String
    Dim val As String
    Dim n As String
    Dim srce As String
    Dim dest As String
'    Dim sender As Outlook.AddressEntry
 
    n = (Format(Now, "dd-mm-yyyy- hh-mm-ss-")) 'the folder name where attachments are saved & converted
EnterVal:
    val = InputBox("Create password of at least 8 characters.")
            If StrPtr(val) = 0 Then 'Cancel was pressed
            ' Handle what to do if cancel pressed
            Exit Sub
            ElseIf Len(strM) < 8 Then 'Not enough characters entered
            MsgBox "You must enter at least 8 characters."
            GoTo EnterVal
            End If

       'Save the attachments to Temporary folder
    Set objFileSystem = CreateObject("Scripting.FileSystemObject")
    varTempFolder = objFileSystem.GetSpecialFolder(2).Path & "\Temp " & n
    MkDir (varTempFolder)
    varTempFolder = varTempFolder & "\"
 
    Set objMail = Outlook.Application.ActiveInspector.CurrentItem
    Set objAttachments = objMail.Attachments
    For Each objAttachment In objAttachments
        objAttachment.SaveAsFile (varTempFolder & objAttachment.FileName)
    Next
    dest = "protectedfiles.zip"
    srce = """" & varTempFolder & "*.*" & """"
    Cmd2 = "CD " & varTempFolder
    cmd3 = "pkzipc.exe -add -passphrase=" & val & " " & "protectedfiles.zip" & " " & srce
    
    Connector = " & "
    Commands = "cmd.exe /c " & Cmd2 & Connector & cmd3
    Debug.Print Commands
    pid = Shell(Commands, vbNormalFocus)
    
Set objAttachments = objMail.Attachments
     While objAttachments.Count > 0
           objAttachments.Item(1).Delete
     Wend

varzipfile = varTempFolder & "protectedfiles.zip"
Pause (2)
objMail.Attachments.Add varzipfile
'DelFolder (varTempFolder)
'Get the address of the person you are sending to
        Dim olObj As Object
        Set olObj = Application.ActiveInspector.CurrentItem
        olObj.Recipients.Item(1).Resolve
        TheMail = olObj.Recipients.Item(1).Address
        Set olObj = Nothing
'Now, email yourself the password
    Dim s As String
    Dim obApp As Object
    Dim NewMail As MailItem
    Set obApp = Outlook.Application
    Set NewMail = obApp.CreateItem(olMailItem)

User = CreateObject("Outlook.Application").GetNamespace("MAPI").CurrentUser.Address
    'You can change the concrete info as per your needs
    With NewMail
         .Subject = TheMail & " Password Sent " & n
         .To = User
         .Body = "Password used was " & """" & val & """"
         '.Attachments.Add ("C:\Attachments\Test File.docx")
         '.Importance = olImportanceHigh
         .Send
    End With
 
    Set obApp = Nothing
    Set NewMail = Nothing
End Sub
Public Sub Pause(Seconds As Single)
    Dim TimeEnd As Single
    TimeEnd = Timer + Seconds
    While Timer < TimeEnd
        DoEvents
    Wend
End Sub

I will eventually clean it up as much as my novice self can do. I will then replace this with the cleaned up version.
 
I suggest you change the program a little and test command in the command prompt. Once you have that working try it in VBA. I added quotes around program exe since it has space.
Sub Zip_Test1()

Dim source As String, Mstr As String, target As String, password As String
Dim file As Variant
Dim cmd As String

Application.DisplayAlerts = False
Mstr = "C:\Users\Desktop\Test"

For Each file In CreateObject("Scripting.FileSystemObject").GetFolder(Mstr).Files
source = Chr$(34) & "C:\Users\Desktop\Test\" & file.Name & Chr$(34)

target = "C:\Users\Desktop\Zipped\"
password = Chr$(34) & "Abcd1234" & Chr$(34)
cmd = """" & "C:\Program Files\PKWARE\PKZIPW\pkzipw.exe" & """" & " -add -pass=" & password & " " & target & " " & source
Debug.Print cmd '' Copy command in Immediate window and paste in Command Prompt.

Shell (cmd)

Exit Sub ''Exit for testing
Next
Application.DisplayAlerts = True
End Sub

Hope this helps!
Regards,
Lewis
 
Status
Not open for further replies.
Similar threads
Thread starter Title Forum Replies Date
H using VBA to edit subject line Outlook VBA and Custom Forms 0
G Get current open draft message body from VBA Outlook VBA and Custom Forms 1
Geldner Problem submitting SPAM using Outlook VBA Form Outlook VBA and Custom Forms 2
P VBA to add email address to Outlook 365 rule Outlook VBA and Custom Forms 0
M Outlook 2016 outlook vba to look into shared mailbox Outlook VBA and Custom Forms 0
V VBA Categories unrelated to visible calendar and Visual appointment Categories Outlook VBA and Custom Forms 2
D Outlook VBA forward the selected email to the original sender’s email ID (including the email used in TO, CC Field) from the email chain Outlook VBA and Custom Forms 3
R Outlook 365 VBA AUTO SEND WITH DELAY FOR EACH EMAIL Outlook VBA and Custom Forms 0
R Outlook 2019 VBA to List Meetings in Rooms Outlook VBA and Custom Forms 0
geoffnoakes Counting and/or listing fired reminders via VBA Using Outlook 1
O VBA - Regex - remove double line spacing Outlook VBA and Custom Forms 1
D.Moore Strange VBA error Outlook VBA and Custom Forms 4
B Modify VBA to create a RULE to block multiple messages Outlook VBA and Custom Forms 0
D Outlook 2021 Using vba code to delete all my spamfolders not only the default one. Outlook VBA and Custom Forms 0
K vba code to auto download email into a specific folder in local hard disk as and when any new email arrives in Inbox/subfolder Outlook VBA and Custom Forms 0
D VBA - unable to set rule condition 'on this computer only' Outlook VBA and Custom Forms 5
L Fetch, edit and forward an email with VBA outlook Outlook VBA and Custom Forms 2
BartH VBA no longer working in Outlook Outlook VBA and Custom Forms 1
W Can vba(for outlook) do these 2 things or not? Outlook VBA and Custom Forms 2
MattC Changing the font of an email with VBA Outlook VBA and Custom Forms 1
P MailItem.To Property with VBA not work Outlook VBA and Custom Forms 2
P Tweak vba so it can target another mailbox Outlook VBA and Custom Forms 1
A Outlook 2010 VBA fails to launch Outlook VBA and Custom Forms 2
richardwing Outlook 365 VBA to access "Other Actions" menu for incoming emails in outlook Outlook VBA and Custom Forms 0
W Create a Quick Step or VBA to SAVE AS PDF in G:|Data|Client File Outlook VBA and Custom Forms 1
J Outlook Rules VBA Run a Script - Multiple Rules Outlook VBA and Custom Forms 0
C Outlook (desktop app for Microsoft365) restarts every time I save my VBA? Using Outlook 1
D VBA Macro to Print and Save email to network location Outlook VBA and Custom Forms 1
TedSch Small vba to kill political email Outlook VBA and Custom Forms 3
E Outlook 365 Outlook/VBA Outlook VBA and Custom Forms 11
N VBA Macro To Save Emails Outlook VBA and Custom Forms 1
Z VBA Forward vs manual forward Outlook VBA and Custom Forms 2
J VBA Cannot programmatically input or change Value for User Defined field Using Outlook 1
J VBA for outlook to compare and sync between calendar Outlook VBA and Custom Forms 1
A Any way to force sort by/group by on search results with VBA? Outlook VBA and Custom Forms 1
E Default shape via VBA Outlook VBA and Custom Forms 4
A Change settings Send/receive VBA Outlook VBA and Custom Forms 0
Z Import Tasks from Access Using VBA including User Defined Fields Outlook VBA and Custom Forms 0
E Outlook VBA change GetDefaultFolder dynamically Outlook VBA and Custom Forms 6
justicefriends How to set a flag to follow up using VBA - for addressee in TO field Outlook VBA and Custom Forms 11
M add new attendee to existing meetings with VBA Outlook VBA and Custom Forms 5
D VBA code to select a signature from the signatures list Outlook VBA and Custom Forms 3
D Create advanced search (email) via VBA with LONG QUERY (>1024 char) Outlook VBA and Custom Forms 2
David McKay VBA to manually forward using odd options Outlook VBA and Custom Forms 1
FryW Need help modifying a VBA script for in coming emails to auto set custom reminder time Outlook VBA and Custom Forms 0
S vba outlook search string with special characters Outlook VBA and Custom Forms 1
S VBA search string with special characters Outlook VBA and Custom Forms 1
U Outlook 2019 VBA run-time error 424 Outlook VBA and Custom Forms 2
DDB VBA to Auto Insert Date and Time in the signature Outlook VBA and Custom Forms 2
F VBA to move email from Non Default folder to Sub folders as per details given in excel file Outlook VBA and Custom Forms 11

Similar threads

Back
Top