【问题标题】:Make VBA wait until batch file is finished让VBA等到批处理文件完成
【发布时间】:2022-11-16 16:49:42
【问题描述】:

我在我的 Access DB 中使用 VBA 来启动一个链接到 PS1 脚本的批处理文件。

一切都按预期工作。问题是我想在该操作完成后运行一些查询,但就目前而言,我需要照看整个事情。所以我正在寻找一种解决方案,以在批处理运行时保持 VBA 暂停。

我找到了这篇文章:https://danwagner.co/how-to-run-a-batch-file-and-wait-until-it-finishes-with-vba/

但由于某种原因,该解决方案对我不起作用。批处理运行,但 VBA 只是继续前进而没有暂停。

这是我的代码:

Private Sub Button_UpdateOffline_Click()

Dim strCommand As String
Dim lngErrorCode As Long
Dim wsh As WshShell
Set wsh = New WshShell

DoCmd.OpenForm "Please_Wait"

'Run the batch file using the WshShell object
strCommand = Chr(34) & _
             "C:\Users\Rip\Q_Update.bat" & _
             Chr(34)
lngErrorCode = wsh.Run(strCommand, _
                       WindowStyle:=0, _
                       WaitOnReturn:=True)
If lngErrorCode <> 0 Then
    MsgBox "Uh oh! Something went wrong with the batch file!"
    Exit Sub
End If

DoCmd.Close acForm, "Please_Wait"

End Sub

如果有帮助,这是我的批处理代码:

START PowerShell.exe -ExecutionPolicy Bypass -Command "& 'C:\Users\Rip\PS1\OfflineFAQ_Update.ps1' "

【问题讨论】:

  • 简单方法:在 VBA 中创建一个文件,启动批处理,让 VBA 等待文件存在,批处理删除文件作为最后一步,VBA 继续...
  • 您应该使用 -File 来运行 PowerShell 脚本,而不是 -Command。例如@Start "PS1" %SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy RemoteSigned -File "C:\Users\Rip\PS1\OfflineFAQ_Update.ps1"

标签: vba powershell ms-access batch-file


【解决方案1】:

您的批处理代码启动 PowerShell,然后关闭。

VBA 会等到您的批处理代码启动 PowerShell,然后继续。它没有办法知道你真的想等到电源外壳已经完成,因为如果你想等待它,你必须让你的批处理脚本也等待。

因此,除了 cmets 中建议的更改之外,要么更改批处理代码以包含 /WAIT

START PowerShell.exe -ExecutionPolicy Bypass -Command "& 'C:UsersRipPS1OfflineFAQ_Update.ps1' "

或者,直接打开 PowerShell,中间没有批处理文件:

strCommand = "PowerShell.exe -ExecutionPolicy Bypass -Command ""& 'C:UsersRipPS1OfflineFAQ_Update.ps1' """

【讨论】:

    猜你喜欢
    • 2011-02-04
    • 1970-01-01
    • 2012-07-19
    • 2012-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多