从Excel VBA宏运行bat文件,然后仅在bat文件执行后执行其他代码

时间:2017-10-17 15:30:45

标签: python excel-vba batch-file vba excel

我通常不会在VBA中编码,但需要创建一个VBA宏,我可以从中运行一个执行python脚本的.bat文件。我已经能够这样做,但是由于程序在excel环境之外运行,我需要确定.bat文件何时完成,并将消息返回到excel环境。 这就是我到目前为止所做的:

Object.keys()

上述.bat文件运行后,如何在excel环境中打印消息,显示.bat文件已执行。 如果我在.bat文件命令之后运行顺序代码(参见上面的代码),由于.bat文件在excel环境之外执行,因此即使.bat文件尚未完成,在此命令之后运行的任何顺序代码也将运行。 有没有办法输出显示.bat文件已执行的消息或参数,然后只在VBA中执行任何顺序代码。

1 个答案:

答案 0 :(得分:1)

完全披露:从Return result from Python to Vba开始略微改编 它本身受Capture output value from a shell command in VBA?

的影响

顺便说一句,如果您只想从VBA执行python脚本,那么请转到here

基本上,您需要创建一个WshShell对象并调用其WshShell.Exec。这将为您提供运行批处理文件的过程的处理,甚至可以用于从stdOut,stdErr等中提取数据。

您需要的VBA代码是:

Public Function runProcess(cmd As String) As String

    Dim oShell As Object
    Dim oExec As Object, oOutput As Object
    Dim s As String, sLine As String

    Set oShell = VBA.CreateObject("Wscript.Shell")    

    Set oExec = oShell.Exec(cmd)
    Set oOutput = oExec.StdOut

    While Not oOutput.AtEndOfStream
        sLine = oOutput.ReadLine
        If sLine <> "" Then s = s & sLine & vbNewLine
    Wend

    Set oOutput = Nothing: Set oExec = Nothing
    Set oShell = Nothing

    runProcess = s

End Function

您可以使用以下命令调用此方法:

Dim out_str As String
out_str = runProcess("c:\IndexTrader\run_file\index_trader.bat")
MsgBox "Script complete!"

使用此方法可获得的额外好处是,您可以捕获该进程输出,从而将消息从python脚本传递回VBA / Excel。

即使您忽略了返回的值,也可以保证在控制返回调用函数时该过程完成。

如果您的.bat文件采用命令行参数,则可以使用:

Dim out_str As String
Dim arg1 As String
arg1 = "6"
out_str = runProcess("c:\IndexTrader\run_file\index_trader.bat " & arg1)
MsgBox "Script complete!"
相关问题