May 14, 2018

Zip Files Using VBA

How to zip files using VBA in Microsoft Excel. Often we need to email files for sharing with others. If the files are large in size then it is better to zip or compress them for saving upload and download times. As you can see in one example a macro enabled file has been compressed from 2.6 MB to about 262 Kb in size.

Watch the video to learn how to compress files using VBA and the inbuilt zipping function in Windows:

Watch this video on Youtube.

Here’s the complete VBA code to perform a compression of files using the Windows inbuilt compression feature:

Sub makeZipFile(pathToZipFolder As Variant, zippedFileName As Variant)

Dim ShellApp As Object

‘First we create an empty zip file
Open zippedFileName For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1

‘Next we copy the files & folders into the zip file
Set ShellApp = CreateObject(“Shell.Application”)
ShellApp.Namespace(zippedFileName).CopyHere ShellApp.Namespace(pathToZipFolder).items

‘We use loopng mechanism to process the zipping with a pause value since zipping the files will take some time
On Error Resume Next
Do Until ShellApp.Namespace(zippedFileName).items.Count = ShellApp.Namespace(pathToZipFolder).items.Count
Application.Wait (Now + TimeValue(“0:00:01”))
On Error GoTo 0

End Sub

Sub zipMyFiles()
Call makeZipFile(“C:\Files-To-Be-Zipped\”, “C:\My-Zipped-Files\”)
End Sub

Further reading:

Zip file(s) with the default Windows zip program (VBA)


2 thoughts on “Zip Files Using VBA

  1. Hi there,
    What is the approach if you try to send to commpressed zip file an empty folder?

  2. Hi sir,

    Am a graduate, since 2014 am learning vba from your online videos its been very simple when you explain and your codes are so direct to understand. I created a vba for zipping the multiple files to Zip folder, previously it was working well but in recent times it is not working. the files are not copying to the zip folder and error msg is ‘File not found or no read permission’ please assist me to resolve the issue sir.

Comments are closed.