Create password-protected zip file

6.3k views Asked by At

I have to zip all the files in a folder and make it password protected.

I googled and found one solution which uses the inbuilt functionality of Windows. The code goes like below:

folder1 = "F:\WLMS_TEAM\TOUHID\Script"
zipfile = "F:\WLMS_TEAM\TOUHID\MyTmp.zip"

Set objFSO = CreateObject("Scripting.FileSystemObject")
objFSO.OpenTextFile(zipfile, 8, True).Write "PK" & Chr(5) & Chr(6) _
  & String(18, Chr(0))

Set ShellApp = CreateObject("Shell.Application")
Set zip = ShellApp.NameSpace(zipfile)
zip.CopyHere folder1
WScript.Sleep 2000

Can I make it password protected?

Or if you can help with some other code to use WinZip (not any other tool) to achieve the same.

Or It would be ok to have a separate code to password protect a pre-generated zip file.

2

There are 2 answers

4
Ansgar Wiechers On

You can run WinZip on the command-line like this:

winzip32.exe -a -s"Password" "C:\path\to\your.zip" *.*

Wrapped in VBScript:

Set sh = CreateObject("WScript.Shell")
sh.Run "winzip32.exe -a -s""Password"" ""C:\path\to\your.zip"" *.*", 0, True

I don't think the Shell.Application object allows the creation of password-protected zip files.

0
Touhid K. On

After a long time of searching, trial and error, I got this working like below: I hope somebody who comes out looking for the similar problems might find it useful.

strWinZipDir = "C:\Program Files\WinZip\WINZIP64.exe"
strZipFileToCreate = LocalPath & "FileName.zip"
strFilesToZip  = LocalPath & "*.txt"

Set objFSO = CreateObject("Scripting.FileSystemObject")

strWinZip = objFSO.GetFile(strWinZipDir).ShortPath
strCommand = strWinzip & " -min -a -s""Password"" -r """ & strZipFileToCreate & """ " & strFilesToZip

Set objShell = CreateObject("WScript.Shell")
Set objExec = objShell.Exec(strCommand)

Do While objExec.Status = 0
 Wscript.Sleep(200)
Loop

Set objShell = Nothing
Set objExec = Nothing
Set objFSO = Nothing