VBAで圧縮解凍処理を行います。
'オプションの意味:変数宣言必須
Option Explicit
'圧縮処理(実行)
Public Sub ZipSample()
ZipFileOrFolder "C:\Test\Files" 'フォルダ圧縮
MsgBox "処理が終了しました。", vbInformation + vbSystemModal
End Sub
'解凍処理(実行)
Public Sub UnZipSample()
UnZipFile "C:\Test\Files\Test.zip"
MsgBox "処理が終了しました。", vbInformation + vbSystemModal
End Sub
'圧縮処理
Public Sub ZipFileOrFolder(ByVal SrcPath As Variant, _
Optional ByVal DestFolderPath As Variant = "")
'ファイル・フォルダをZIP形式で圧縮
'SrcPath:元ファイル・フォルダ
'DestFolderPath:出力先、指定しない場合は元ファイル・フォルダと同じ場所
Dim DestFilePath As Variant
With CreateObject("Scripting.FileSystemObject")
If IsFolder(DestFolderPath) = False Then
If IsFolder(SrcPath) = True Then
DestFolderPath = SrcPath
ElseIf IsFile(SrcPath) = True Then
DestFolderPath = .GetFile(SrcPath).ParentFolder.Path
Else: Exit Sub
End If
End If
DestFilePath = AddPathSeparator(DestFolderPath) & _
.GetBaseName(SrcPath) & ".zip"
'空のZIPファイル作成
With .CreateTextFile(DestFilePath, True)
.Write ChrW(&H50) & ChrW(&H4B) & ChrW(&H5) & ChrW(&H6) & String(18, ChrW(0))
.Close
End With
End With
With CreateObject("Shell.Application")
With .NameSpace(DestFilePath)
.CopyHere SrcPath
While .Items.Count < 1
DoEvents
Wend
End With
End With
End Sub
'解凍処理
Public Sub UnZipFile(ByVal SrcPath As Variant, _
Optional ByVal DestFolderPath As Variant = "")
'ZIPファイルを解凍
'SrcPath:元ファイル
'DestFolderPath:出力先、指定しない場合は元ファイルと同じ場所
'※出力先に同名ファイルがあった場合はユーザー判断で処理
With CreateObject("Scripting.FileSystemObject")
If .FileExists(SrcPath) = False Then Exit Sub
If LCase(.GetExtensionName(SrcPath)) <> "zip" Then Exit Sub
If IsFolder(DestFolderPath) = False Then
DestFolderPath = .GetFile(SrcPath).ParentFolder.Path
End If
End With
With CreateObject("Shell.Application")
.NameSpace(DestFolderPath).CopyHere .NameSpace(SrcPath).Items
End With
End Sub
'フォルダチェック処理
Private Function IsFolder(ByVal SrcPath As String) As Boolean
IsFolder = CreateObject("Scripting.FileSystemObject").FolderExists(SrcPath)
End Function
'ファイルチェック処理
Private Function IsFile(ByVal SrcPath As String) As Boolean
IsFile = CreateObject("Scripting.FileSystemObject").FileExists(SrcPath)
End Function
'ファイルパスセパレータ追加処理
Private Function AddPathSeparator(ByVal SrcPath As String) As String
If Right(SrcPath, 1) <> ChrW(92) Then SrcPath = SrcPath & ChrW(92)
AddPathSeparator = SrcPath
End Function