Shell
関数ではなくWScript.Shell
オブジェクトのRun
メソッドを使用し、そのメソッドの第二引数にTrue
を指定して同期的に実行する必要があります。これにより、Pythonスクリプトが終了するまでVBAコードの実行が待機状態になります。
以下のコードは、Pythonスクリプトの同期実行とエラーログのチェックを組み合わせた例です。
Access VBA コード例(同期実行とエラーログチェック)
Sub ExportTableToCSVAndRunPythonWithSyncAndLogCheck() Dim tableName As String Dim exportFilePath As String Dim pythonScriptPath As String Dim shell As Object Dim errLogPath As String Dim fileNum As Integer Dim lineCount As Long Dim textLine As String Dim N As Long ' エラーログの閾値 ' 設定 tableName = "YourTableName" exportFilePath = "C:\path\to\your\exportedFile.csv" pythonScriptPath = "C:\path\to\your\script.py" errLogPath = "C:\path\to\your\errlog.txt" N = 5 ' この数を超えるエラーがあった場合に警告 ' テーブルをCSV形式でエクスポート DoCmd.TransferText TransferType:=acExportDelim, TableName:=tableName, FileName:=exportFilePath, HasFieldNames:=True ' Pythonスクリプトを同期的に実行 Set shell = CreateObject("WScript.Shell") shell.Run "python """ & pythonScriptPath & """ """ & exportFilePath & """", 1, True ' エラーログの行数をチェック fileNum = FreeFile() Open errLogPath For Input As fileNum lineCount = 0 Do Until EOF(fileNum) Line Input fileNum, textLine lineCount = lineCount + 1 Loop Close fileNum ' エラーログの行数がNを超えたらメッセージボックスを表示 If lineCount > N Then MsgBox "エラーログに" & lineCount & "件のエラーがあります。詳細は " & errLogPath & " を確認してください。", vbCritical, "エラー通知" End If End Sub
このコードでは、WScript.Shell
のRun
メソッドを使用してPythonスクリプトを実行しています。Run
メソッドの第三引数にTrue
を指定することで、スクリプトの実行が完了するまで処理を待機させています。これにより、Pythonスクリプトから出力されるエラーログの行数を正確にカウントする前にスクリプトが完全に終了することを保証します。