Option Explicit
Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Private Const FOF_SILENT = &H4
Private Const FOF_RENAMEONCOLLISION = &H8
Private Const FOF_NOCONFIRMATION = &H10
Private Const FOF_ALLOWUNDO = &H40
Private Const FOF_FILESONLY = &H80
Private Const FOF_SIMPLEPROGRESS = &H100
Private Const FOF_NOCONFIRMMKDIR = &H200
Private Const FOF_NOERRORUI = &H400
Private Const FOF_NOCOPYSECURITYATTRIBS = &H800
Private Const FOF_NORECURSION = &H1000
Private Const FOF_NO_CONNECTED_ELEMENTS = &H2000
Public Sub Create_Zip_Files()
Dim PDFsFolder As String
Dim ZIPsFolder As String
Dim files As Variant
Dim inputFiles As String, outputZipFile As String
Dim prefix As String
Dim i As Long
PDFsFolder = "C:\path\to\PDF files\"
ZIPsFolder = "C:\path\to\zip files\"
If Right(PDFsFolder, 1) <> "\" Then PDFsFolder = PDFsFolder & "\"
If Right(ZIPsFolder, 1) <> "\" Then ZIPsFolder = ZIPsFolder & "\"
With ActiveSheet
files = .Range("A2:B" & .Cells(.Rows.Count, "A").End(xlUp).Row + 1)
End With
prefix = ""
inputFiles = ""
For i = 1 To UBound(files)
If Left(files(i, 1), 3) <> prefix Then
If inputFiles <> "" Then
Zip_Files inputFiles, outputZipFile
End If
prefix = Left(files(i, 1), 3)
inputFiles = PDFsFolder & files(i, 1)
outputZipFile = ZIPsFolder & files(i, 2)
Else
inputFiles = inputFiles & "|" & PDFsFolder & files(i, 1)
End If
Next
MsgBox "Done"
End Sub
Private Sub Zip_Files(ByVal inputFiles As String, ByVal outputZipFile As Variant)
Dim FSO As Object
Dim WShell As Object
Dim WShtempFolder As Object
Dim WShZipFolder As Object
Dim file As Variant
Dim CopyHereFlags As Variant
Dim tempFolder As Variant, tempZipFolder As Variant
tempFolder = Environ("temp")
tempZipFolder = tempFolder & "\temp zip"
Set FSO = CreateObject("Scripting.FileSystemObject")
Set WShell = CreateObject("Shell.Application")
If FSO.FolderExists(tempZipFolder) Then FSO.DeleteFolder tempZipFolder, True
Set WShtempFolder = WShell.Namespace(tempFolder)
WShtempFolder.NewFolder Mid(tempZipFolder, InStrRev(tempZipFolder, "\") + 1)
Set WShtempFolder = WShell.Namespace(tempZipFolder)
CopyHereFlags = FOF_SILENT + FOF_RENAMEONCOLLISION + FOF_NOCONFIRMATION + FOF_NOERRORUI
For Each file In Split(inputFiles, "|")
WShtempFolder.CopyHere file, CopyHereFlags
DoEvents
Next
NewZip outputZipFile
Set WShZipFolder = WShell.Namespace(outputZipFile)
WShZipFolder.CopyHere WShtempFolder.Items, CopyHereFlags
Do
DoEvents
Sleep 100
Loop Until WShZipFolder.Items.Count = WShtempFolder.Items.Count
Set FSO = Nothing
Set WShell = Nothing
End Sub
Private Sub NewZip(sPath)
On Error Resume Next
While Len(Dir(sPath)) > 0
Kill sPath
Wend
On Error GoTo 0
Open sPath For Output As #1
Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
Close #1
End Sub