Zip and Unzip Files with VBScript and 7Zip

Occasionally it is really handy to zip and unzip files before you copy them around, or you want to archive them automatically for storage. I often use 7Zip for this task because it’s free and open source, has a great compression ratio, and supports a ton of formats.

Since 7Zip is such a handy tool I thought I’d whip up a script to utilize it’s command line version called 7z.exe so that I could call it from VBScript. You can use these functions to compress or uncompress files or folders.

If you want to use this script to compress more than one file at a time you can do this 2 distinct ways. By calling each file in the local directory like this:

Or you could specify the wild card character like this:

In the second example I used the double quotes because my path included spaces. Be sure to include this any time you have a file that has spaces in it’s name or path. You can pass as many files as you want using these methods.

When using the unzip function, if the folder you select to extract to doesn’t exist. It will be created automatically by 7z.exe.

 

12 thoughts on “Zip and Unzip Files with VBScript and 7Zip

  1. If you find this and can afford to take time out of your busy schedule, could you explain the use of quotes in your oShell.Run statement?

    I am learning vbscript. I wrote a script implementing 7zip to unzip a large number of zip files stored in many folders, but no matter how I formatted my oShell.Run statement, I could not get it to work.

    I found your example online, substituted one line of your code for mine, and it worked. If you would explain each quote (or combination) so I can understand why my script didn’t work and yours does, I would greatly appreciate it, but don’t feel pressured. I will eventually figure it out. 😉 Do it only if you have the time and you feel like it.

    oShell.Run “””” & s7zLocation & “7za.exe”” e -y -o””” & sLocation & “”” “”” & _
    sArchiveName & “”””

    Thanks, and if you don’t have time or just don’t want to do it, that’s cool. I’ll figure it out eventually.

    • The problem has to do with spaces in the file path, and the potential spaces in the location you’re trying to zip and the location you’re trying to store your archive. So, four quotes in a row is saying, pass the quote character as a string to the command line. So instead of passing this, which would fail:

      C:\Program Files (x86)\7zip\7za.exe e -y -o c:\zipthis c:\myarchive.zip

      Pass this to the command line:

      “C:\Program Files (x86)\7zip\7za.exe” e -y -o “c:\zipthis” “c:\myarchive.zip”

      The second option accounts for the fact that “C:\Program Files (x86)” has a space in the path.

  2. Hi there, im really sorry to be a pain, but can you pls put in some sample file locations, I am a total newbie to vbs and just merely copying your code doesn’t work for me.

  3. Thanks Nate, this is what I am trying to do….

    Firstly i manually extract my zip files to folder using 7zip on Win 8.1 (This is what I want to incorporate into my code).

    Then I kick off the code which does the following.

    Opens the manually extracted xlsx file using a loop
    renames the file
    saveas xls
    then deletes the original xlsx
    finally delete the zip files,

    This sequence is repeated for 3 files.

    The reason I have a loop is that I can only guarantee the first two words of the file name to be static.

    My desire is to have your unzip routine incorporated into my code, strangely ive tried to run it as is and nothing happens, I then checked the 7zip program folder and in Win 8.1 64bit there is no 7za.exe, there is 7z.exe and 7zFM.exe, ive tried changing it to both and nothing happens, no errors.

    'launch Excel and open file
    Const xlExcel8 = 56
    Const xlOpenXMLWorkbook = 51
    Set xlObj = CreateObject("Excel.Application")
    Set fso = CreateObject("Scripting.FileSystemObject")

    Set re = New RegExp
    re.Pattern = "^Weekly Opened.*\.xlsx$"
    re.IgnoreCase = True

    For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\Process\_ThisWeek").Files
    If re.Test(f.Name) Then
    Set xlFile = xlObj.WorkBooks.Open(f.Path)

    'turn off screen alerts
    xlObj.Application.DisplayAlerts = FALSE

    xlfile.SaveAs "C:\Users\Jimbo\Documents\Process\_ThisWeek\Ready\Weekly Opened.xls", xlExcel8
    xlFile.Close True

    End If
    Next

    Set re = New RegExp
    re.Pattern = "^Weekly Fixed.*\.xlsx$"
    re.IgnoreCase = True

    For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\Process\_ThisWeek").Files
    If re.Test(f.Name) Then
    Set xlFile = xlObj.WorkBooks.Open(f.Path)

    'turn off screen alerts
    xlObj.Application.DisplayAlerts = FALSE

    xlfile.SaveAs "C:\Users\Jimbo\Documents\Process\_ThisWeek\Ready\Weekly Fixed.xls", xlExcel8
    xlFile.Close True
    End If
    Next

    Set re = New RegExp
    re.Pattern = "^Weekly Outstanding.*\.xlsx$"
    re.IgnoreCase = True

    For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\Process\_ThisWeek").Files
    If re.Test(f.Name) Then
    Set xlFile = xlObj.WorkBooks.Open(f.Path)

    'turn off screen alerts
    xlObj.Application.DisplayAlerts = FALSE

    xlfile.SaveAs "C:\Users\Jimbo\Documents\Process\_ThisWeek\Ready\Weekly Outstanding.xls", xlExcel8
    xlFile.Close True
    End If
    Next

    Set re = New RegExp
    re.Pattern = "^Weekly.*\.xlsx$"
    re.IgnoreCase = True

    For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\Process\_ThisWeek").Files
    If re.Test(f.Name) Then
    fso.Deletefile(f.Path)
    End If
    Next

    Set re = New RegExp
    re.Pattern = "^Weekly.*\.zip$"
    re.IgnoreCase = True

    For Each f In fso.GetFolder("C:\Users\Jimbo\Documents\Process\_ThisWeek").Files
    If re.Test(f.Name) Then
    fso.Deletefile(f.Path)
    End If
    Next

    xlObj.Quit

    • Good catch. This post is pretty old, and 7Zip has changed the file structure a little bit. So the command line version of 7Zip is now called 7Z.exe and not 7Za.exe like it used to be called. I’ve updated the code accordingly.

      Give it a try now, it should still work just fine using the example lines I posted above.

  4. Hi Nate, thanks for adjusting the code.

    Im a little bit perplexed here, am I to just copy this segment of code, put the vbs file in the same folder as the zip and run it? if yes then it doesn’t work for me. Nothing happens, not even an error.

    Function UnZip(sArchiveName,sLocation)
    ‘This script is provided under the Creative Commons license located
    ‘at http://creativecommons.org/licenses/by-nc/2.5/ . It may not
    ‘be used for commercial purposes with out the expressed written consent
    ‘of NateRice.com

    Set oFSO = WScript.CreateObject(“Scripting.FileSystemObject”)
    Set oShell = WScript.CreateObject(“Wscript.Shell”)

    ‘——–Find Working Directory——–
    aScriptFilename = Split(Wscript.ScriptFullName, “\”)
    sScriptFilename = aScriptFileName(Ubound(aScriptFilename))
    sWorkingDirectory = Replace(Wscript.ScriptFullName, sScriptFilename, “”)
    ‘————————————–

    ‘——-Ensure we can find 7z.exe——
    If oFSO.FileExists(sWorkingDirectory & “\” & “7z.exe”) Then
    s7zLocation = “”
    ElseIf oFSO.FileExists(“C:\Program Files\7-Zip\7z.exe”) Then
    s7zLocation = “C:\Program Files\7-Zip\”
    Else
    UnZip = “Error: Couldn’t find 7z.exe”
    Exit Function
    End If
    ‘————————————–

    ‘-Ensure we can find archive to uncompress-
    If Not oFSO.FileExists(sArchiveName) Then
    UnZip = “Error: File Not Found.”
    Exit Function
    End If
    ‘————————————–

    oShell.Run “””” & s7zLocation & “7z.exe”” e -y -o””” & sLocation & “”” “”” & _
    sArchiveName & “”””, 0, True
    UnZip = 1
    End Function

  5. Hi, cant get your code to work on the vba in excel 2016. It cant find the file system object , but i have referenced the dll as norm (syswow64/scrrun.dll). Now its been almost a decade since i last did any vb/vba coding and i am rusty to say the least. Any chance you put a snapshot of the references on the page. Google seems to bring back old examples that are no longer relevant.

  6. Error is 424 , object required.
    It was a late night last night, and on closer examination It look like its the Wscript, that is the issue not the file system object as if i insert
    Set objFSO = New FileSystemObject
    Before
    Set oFSO = Wscript.CreateObject(“Scripting.FileSystemObject”)
    the debug still highlights the Wscript.

    Have never needed to use Wscript before , so this is a learning curve. since intellisense does not seem to pick up Wscript , what reference do i need?

  7. Forgot to add, i already have a reference for windows script host object model (syswow64/wshom.ocx) and yet intelisense does not pick it up and i still get error 424.

Leave a Comment