' Add references via Tools --> References:
' 1) Microsoft Shell Controls And Automation
' 2) Microsoft Scripting Runtime
' 3) Microsoft Office xx.x Object Library
Public Sub UnzipFiles()
On Error GoTo ErrHandler
Dim objFileSystem As New Scripting.FileSystemObject
Dim objFileDialog As Office.FileDialog
Dim objShell As New Shell32.Shell
Dim astrFilePaths() As String
Dim strFullFolder As String
Dim strTopFolder As String
Dim strSubfolder As String
Dim intNumFiles As Integer
Dim blnErrors As Boolean
Dim i As Integer
' Present user with multi-select file dialog
' to select the zip files for processing:
Set objFileDialog = Application.FileDialog(msoFileDialogOpen)
With objFileDialog
.Title = "Select Files to Unzip"
.AllowMultiSelect = True
.InitialFileName = ThisWorkbook.Path & "\"
.Filters.Clear
.Filters.Add "Zip Files", "*.zip"
.ButtonName = "Unzip"
If .Show Then
intNumFiles = .SelectedItems.Count
ReDim astrFilePaths(1 To intNumFiles)
For i = 1 To intNumFiles
astrFilePaths(i) = .SelectedItems(i)
Next i
Else
GoTo ExitProc
End If
End With
' Create new directory for the extracted files
strTopFolder = objFileSystem.GetFile(astrFilePaths(1)).ParentFolder.Path & "\Extracted Files\"
If Not objFileSystem.FolderExists(strTopFolder) Then
objFileSystem.CreateFolder strTopFolder
End If
' Extract files to the new directory
For i = 1 To intNumFiles
strSubfolder = objFileSystem.GetBaseName(astrFilePaths(i)) & "\"
strFullFolder = strTopFolder & strSubfolder
If Not objFileSystem.FolderExists(strFullFolder) Then
objFileSystem.CreateFolder strFullFolder
End If
On Error Resume Next
objShell.Namespace(strFullFolder).CopyHere objShell.Namespace(astrFilePaths(i)).Items
If Err.Number <> 0 Then blnErrors = True
On Error GoTo ErrHandler
Next i
' Notify user of results
MsgBox Format(intNumFiles, "#,0") & " zip files were extracted with " _
& IIf(blnErrors, "some", "no") & " errors to this location:" _
& vbCrLf & vbCrLf & strTopFolder, vbInformation
' Show the extracted files in file explorer
objShell.ShellExecute "explorer.exe", strTopFolder
ExitProc:
Set objFileSystem = Nothing
Set objFileDialog = Nothing
Set objShell = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitProc
End Sub