0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

7-zipでパスワード付きzipファイルを作成するVBAコード

Posted at
Sub TEST001()

    Dim pdf1 As String
    Dim pdf2 As String
    Dim pdf3 As String
    
    pdf1 = "C:\Users\user\OneDrive\ドキュメント\PDF\test1.pdf"
    pdf2 = "C:\Users\user\OneDrive\ドキュメント\PDF\test2.pdf"
    pdf3 = "C:\Users\user\OneDrive\ドキュメント\PDF\test3.pdf"
    
    Call CreateZipWithPassword("hogehoge", pdf1, pdf2, pdf3)

End Sub
'// ParamArray であたえられたファイルたち(paths)を
'// 7-zip でパスワード(pass_word)付きZipにする

Sub CreateZipWithPassword(ByVal pass_word As String, ParamArray paths())

    Dim sevenZipPath As String      '-- 7-Zipのパス
    sevenZipPath = "C:\Program Files\7-Zip\7z.exe"
    
    Dim zipArchiveName As String    '-- 出力するZipファイル名
    zipArchiveName = Format(Now, "yyyy-mm-dd[hnnss]") & ".zip"
    
    Dim zipArchivePath As String    '-- 出力するZipファイルのパス
    With CreateObject("Scripting.FileSystemObject")
        zipArchivePath = .BuildPath(.GetParentFolderName(paths(0)), zipArchiveName)
    End With
    
    Dim i As Long
    Dim filesPathStr As String
    
    For i = LBound(paths) To UBound(paths)
     '' アーカイブするファイルたちのパスを半角スペースでつなげる
        filesPathStr = filesPathStr & GetExistsPathWQ(paths(i)) & " "
    Next i
    
    Dim cmdLine As String   '-- コマンドライン
    cmdLine = AddWQ(sevenZipPath) & " a -tzip " & AddWQ(zipArchivePath) & _
              " " & filesPathStr & "-p" & pass_word
 
 '' コマンド実行
    Shell cmdLine, vbHide
    
    MsgBox "Zipファイル作成完了!", vbInformation

End Sub
'// ファイルパスなどの文字列をダブルクォーテーション付きで返す

Function AddWQ(ByVal file_path As String) As String

    AddWQ = Chr(34) & file_path & Chr(34)

End Function
'// ファイルが存在すればダブルクォーテーション付きのパスを返す

Function GetExistsPathWQ(ByVal file_path As String) As String

    With CreateObject("Scripting.FileSystemObject")
        If .FileExists(file_path) Then
            GetExistsPathWQ = AddWQ(file_path)
        End If
    End With
    
End Function
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?