VBA(バッチファイル実行)

 

https://vbabeginner.net/execute-batch-file/
https://www.bugbugnow.net/2018/06/wshrunexec.html
http://officetanaka.net/excel/vba/tips/tips75.htm

https://qiita.com/aki3061/items/b4f4bc5f4ef3fa015c5f

※「Windows Script Host Object Model」を参照設定で追加して再起動必要

 

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

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


Private Sub CommandButton1_Click()

Dim wsh As Object
Dim res As WshExec
Dim lines() As String
Dim buf As String

'画面を更新しない
Application.ScreenUpdating = False
'確認メッセージを表示しない
Application.DisplayAlerts = False

'''''''''''''''''''''''''''''''''''''
'テスト用ファイル作成

Open ActiveWorkbook.Path & "\a.sql" For Output As #1
  Print #1, "select * from tab1;"
Close #1

Open ActiveWorkbook.Path & "\a.bat" For Output As #1
  Print #1, "mysql -h 192.168.137.66 -uroot -p""password"" -D test < " & ActiveWorkbook.Path & "\" & "a.sql"
Close #1

'コマンド実行してテキストファイル書込
Set wsh = CreateObject("WScript.Shell")
Set res = wsh.Exec(ActiveWorkbook.Path & "\a.bat")

'Statusは、起動したプログラムが実行中であれば0を、実行が完了していれば1を返す。

Do While res.Status = 0
DoEvents
Loop

Debug.Print (res.ExitCode)


lines = Split(res.StdOut.ReadAll, vbCrLf)

Open ActiveWorkbook.Path & "\a.log" For Output As #1
For Each Line In lines
'ログではパスワードを置き換え
Print #1, Replace(Replace(Line, "password", "XXXXX"), "YWRtaW46YWRtaW4=", "XXXXX")
Next Line
Close #1

'エラー判定
If res.ExitCode <> 0 Then
  MsgBox ("処理異常発生1")
  GoTo errend
End If


'''''''''''''''''''''''''''''''''''''
'テスト用ファイル作成

Open ActiveWorkbook.Path & "\b.json" For Output As #1
  Print #1, "{"
  Print #1, """name"" : ""project123"","
  Print #1, """description"" : ""description of project123"""
  Print #1, "}"
Close #1

Open ActiveWorkbook.Path & "\b.bat" For Output As #1
  Print #1, "cd C:\curl-8.0.1_8-win64-mingw\bin && curl -X POST ""http://localhost:9090/webadmin/denodo-scheduler-admin/public/api/projects?uri=//localhost:8000"" -H ""Authorization: Basic YWRtaW46YWRtaW4="" -H ""Content-Type: application/json"" -d @" & ActiveWorkbook.Path & "\" & "b.json"
Close #1

'コマンド実行してテキストファイル書込
Set wsh = CreateObject("WScript.Shell")
Set res = wsh.Exec(ActiveWorkbook.Path & "\b.bat")

Do While res.Status = 0
DoEvents
Loop

Debug.Print (res.ExitCode)


lines = Split(res.StdOut.ReadAll, vbCrLf)

Open ActiveWorkbook.Path & "\b.log" For Output As #1
For Each Line In lines
'ログではパスワードを置き換え
Print #1, Replace(Replace(Line, "password", "XXXXX"), "YWRtaW46YWRtaW4=", "XXXXX")
Next Line
Close #1

'エラー判定
If res.ExitCode <> 0 Then
  MsgBox ("処理異常発生2")
  GoTo errend
End If


'''''''''''''''''''''''''''''''''''''

 

MsgBox ("処理完了")

errend:

Set res = Nothing
Set wsh = Nothing


'確認メッセージを表示する
Application.DisplayAlerts = True
'画面を更新する
Application.ScreenUpdating = True

'バッチファイルを削除
Kill ActiveWorkbook.Path & "\*.bat"
End Sub