Monday, April 02, 2007

Zip And UnZip In Access Without WinZip

Not all users will have WinZip on their PC. The following VBA code using the OpenSource CodeGuru Zip DLL library offers a simple and effective way to manage ZIP files during application installation and within applications. I have used this basic code in an application without mishap.

1. Download the DLL's and source code from: http://www.codeguru.com/vb/gen/vb_graphics/fileformats/article.php/c6743/

2. Deploy the DLL, CGZipLibrary.dll, to the application folder or to the .../Windows/System32 folder

3. Add a Reference to the DLL

4. Use VBA code based on the following sample Access form module:

' Unzip/Zip Client program for the CGZipLibrary ActiveXDLL
' Based on VB6 Code by Chris Eastwood, July 1999
Option Explicit

Private Declare Function GetTempPath Lib "kernel32" Alias "GetTempPathA" (ByVal nBufferLength As Long, ByVal lpBuffer As String) As Long

Private Function GetTempPathName() As String
Dim sBuffer As String
Dim lRet As Long

sBuffer = String$(255, vbNullChar)
lRet = GetTempPath(255, sBuffer)
If lRet > 0 Then
sBuffer = Left$(sBuffer, lRet)
End If
GetTempPathName = sBuffer
End Function

Private Sub cmdUnZip_Click()
On Error GoTo vbErrorHandler

' Unzip the ZIPTEST.ZIP file to the Windows Temp Directory'
Dim oUnZip As CGUnzipFiles
Set oUnZip = New CGUnzipFiles
With oUnZip
' Which Zip File ?
.ZipFileName = "C:\ZIPTEST.ZIP"
' Where are we zipping to ?'
.ExtractDir = GetTempPathName
'Keep Directory Structure of Zip ?'
.HonorDirectories = False
' Unzip and Display any errors as required
If .Unzip <> 0 Then
MsgBox .GetLastMessage
End If
End With
Set oUnZip = Nothing
MsgBox "\ZIPTEST.ZIP Extracted Successfully to " & GetTempPathName

Exit Sub
vbErrorHandler:
MsgBox Err.Number & Err.Description
End Sub

Private Sub cmdZip_Click()
On Error GoTo vbErrorHandler

Set oZip = New CGZipFiles
With oZip'
' Give Zip File a Name\Path
.ZipFileName = "\ZIPTEST.ZIP"
.UpdatingZip = False ' ensures a new zip is created
' Add in the files to the zip - in this case - all the files in the current directory
.AddFile App.Path & "\*.*"
' Make the zip file & display any errors
If .MakeZipFile <> 0 Then
MsgBox .GetLastMessage ' any errors
End If
End With
Set oZip = Nothing
MsgBox "\ZIPTEST.ZIP Created Successfully"

Exit Sub
vbErrorHandler:
MsgBox Err.Number & Err.Description
End Sub

No comments: