VBA(PowerShell実行)

 

https://extan.jp/?p=10164
https://qiita.com/Qiitacky/items/a08211ed77a4670e7860
https://pcnote.me/post/powershell-zip/


-- 1. 開発タブの挿入でボタンを作成
ActiveXコントロールのものを使用する

-- 2. デザインモードONで作成したボタンをダブルクリックするとエディタが開くので下記コードを記載。デザインモードOFFで実行

Option Explicit


Private Sub CommandButton1_Click()

    '画面を更新しない
    Application.ScreenUpdating = False
    '確認メッセージを表示しない
    Application.DisplayAlerts = False
    
    
    Dim wsh As Object
    Set wsh = CreateObject("WScript.Shell")
    
    Dim ret As Long
    
    'テスト用ファイル作成
    
    Open ThisWorkbook.Path & "\a.txt" For Output As #1
        Print #1, "test"
    Close #1
    
    Dim psCmd As String
    
    'aファイルをコピー
    psCmd = "Copy-Item -Path " & ThisWorkbook.Path & "\a.txt" & " -Destination " & ThisWorkbook.Path & "\b.txt"
    ret = wsh.Run(Command:="powershell -ExecutionPolicy RemoteSigned -Command " & psCmd, WindowStyle:=0, WaitOnReturn:=True)
    Debug.Print ret
    
    'bファイルを圧縮
    psCmd = "Compress-Archive -Path " & ThisWorkbook.Path & "\b.txt" & " -DestinationPath " & ThisWorkbook.Path & "\b.zip"
    ret = wsh.Run(Command:="powershell -ExecutionPolicy RemoteSigned -Command " & psCmd, WindowStyle:=0, WaitOnReturn:=True)
    Debug.Print ret
    
    
    'bファイルをリネーム
    Name ThisWorkbook.Path & "\b.txt" As ThisWorkbook.Path & "\b.old.txt"
    
    
    'bファイルを解凍
    psCmd = "Expand-Archive -Path " & ThisWorkbook.Path & "\b.zip" & " -DestinationPath " & ThisWorkbook.Path
    ret = wsh.Run(Command:="powershell -ExecutionPolicy RemoteSigned -Command " & psCmd, WindowStyle:=0, WaitOnReturn:=True)
    Debug.Print ret
    
    
    
    MsgBox ("処理完了")
    
    
    Set wsh = Nothing
    
    
    '確認メッセージを表示する
    Application.DisplayAlerts = True
    '画面を更新する
    Application.ScreenUpdating = True

End Sub