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)