![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBAで
・ファイル/フォルダをZIP圧縮
できます!
※ここで紹介するのは「パスワード無しZIPファイル」の作成(圧縮)方法です。
![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
VBAから
・Power Shellのコマンドレットを実行
することで実現します!
※コマンドレット「Compress-Archive」により実現します。
![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
実行結果も取得できます!
※正常終了の場合、実行結果は「0」になります。
※異常終了の場合、実行結果は「1」になります。
![](https://excel-vba.work/wp-content/themes/cocoon-master/images/b-woman.png)
ZIP形式(パスワード付き)で圧縮するすることも
できます!
詳細は以下の記事をご確認ください!
はじめに
他のサイトでは
・「CopyHere」メソッドなるもので圧縮する方法
が紹介されていたりしますが、こちらは動作保証されていません。
※公式サイトに動作保証していない旨が記載されています。
VBAコード
ここでは例として
・デスクトップ配下の約1GBのフォルダ「test」を圧縮し
・デスクトップ配下にファイル「test.zip」として作成
します。
![フォルダ「test」](https://excel-vba.work/wp-content/uploads/2021/12/vba_zipfile_compress-archive_001.png)
![フォルダ「test」のサイズは約1GB](https://excel-vba.work/wp-content/uploads/2021/12/vba_zipfile_compress-archive_003.png)
Option Explicit
Sub execPsCommand()
Dim targetPath As String
Dim zipFilePath As String
Dim psCommand As String
Dim wsh As Object
Dim result As Integer
'ZIP形式で圧縮するフォルダ(またはファイル)パスを指定
targetPath = "C:\Users\user\Desktop\test"
'作成するZIPファイルのパスを指定
zipFilePath = "C:\Users\user\Desktop\test.zip"
'実行するPowerShellのコマンドレットを組み立て
psCommand = "powershell -NoProfile -ExecutionPolicy Unrestricted Compress-Archive -Path " & targetPath & " -DestinationPath " & zipFilePath & " -Force"
Set wsh = CreateObject("WScript.Shell")
'PowerShellのコマンドレットを実行
result = wsh.Run(command:=psCommand, WindowStyle:=0, WaitOnReturn:=True)
If (result = 0) Then
MsgBox ("圧縮が正常終了しました。")
Else
MsgBox ("圧縮が異常終了しました。")
End If
'後片付け
Set wsh = Nothing
End Sub
実行結果
フォルダをZIP形式で圧縮できました。
※「フォルダ」でなく「ファイル」でも圧縮できます。
![実行結果①](https://excel-vba.work/wp-content/uploads/2022/01/vba_zipfile_compress-archive_006.png)
![実行結果②](https://excel-vba.work/wp-content/uploads/2021/12/vba_zipfile_compress-archive_004.png)
サイズが圧縮されていることも確認できました。
※「約1GB」から「約0.2GB(=約200MB)」へ圧縮されました。
![実行結果③](https://excel-vba.work/wp-content/uploads/2021/12/vba_zipfile_compress-archive_005.png)
参考①
ZIP形式のファイルを解凍(展開)することもできます。
詳細は以下の記事をご確認ください。
参考②
圧縮する前に、圧縮するファイル/フォルダの存在確認をしたほうがよいです。
ファイル/フォルダの存在確認の詳細は、以下の記事をご確認ください。
参考③
上記で使用した以下の詳細は、公式サイトをご確認ください。
●Power Shellのコマンドレット「Compress-Archive」