How to Zip File or Folder using VBA Code – Excel Macro?

VBA Code to Zip File or Folder

Just like this Unzip vba code, this also uses the Windows default file compressor.

There is only one difference between this code and Unzip.

Yuo just have to swap the parameters & Create a empty Zip file at first.

  1. Zip file path &
  2. Folder location.

The first parameters takes the Zip file name to be created. Second parameter is the folder location that has the files to be compressed or a complete file path.

Zip VBA Macro

Use this code to Zip a file or folder. But just modify the input parameters in it, before hitting F5.

Sub ZipVBA()
    'Define Variable Data Types
    'Early Binding Reference
    'Add Tools -> Reference -> "Microsoft Shell Controls & Automation"
    Dim zipFileName As String
    Dim unZipFolderName As String
    Dim objZipItems As FolderItems
    Dim objZipItem As FolderItem
    
    'Set Zip File Name & Folder path to Unzip
    zipFileName = "PathToZipFile\FilewithFullPath.zip"
    unZipFolderName = "Extract\To\Path"
    
    'Create Empty Zip file
    Open zipFileName For Output As #1
        Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    Close #1
    
    'Initialize Shell Object & File to be Zipped
    Dim wShApp As Shell
    Set wShApp = CreateObject("Shell.Application")
    Set objZipItems = wShApp.Namespace(unZipFolderName).Items
    
    'Method1: Compress All Files at once
    wShApp.Namespace(zipFileName).CopyHere objZipItems
    Do Until wShApp.Namespace(zipFileName).Items.Count = objZipItems.Count
        DoEvents
        Debug.Print "Processing " & wShApp.Namespace(zipFileName).Items.Count & " of" & objZipItems.Count
        Application.Wait DateAdd("s", 1, Now)
    Loop
    Debug.Print "Processing " & wShApp.Namespace(zipFileName).Items.Count & " of" & objZipItems.Count
    
    'Method2: ZIP Files One by one
    For Each objZipItem In objZipItems
        If objZipItem.Name = "FileName.ext" Then
            wShApp.Namespace(zipFileName).CopyHere objZipItem
        End If
    Next
    
End Sub

In some cases, you might get Object or variable not defined error, if you have not followed the exact order of code or missed any line mentioned above.

Once the code executes successfully, you will get a zip file.

This compressed file can be uncompressed using Windows default app without using third party compressor apps like Winzip or winrar.

This code is very useful when you would like to archive the old log files generated by the vba code. Or when the code is sending email & many files has to be sent as attachment.

Instead of attaching many files, this code can zip all the files and can be attached as one single compressed file.