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

2024-10-01 19:24:26 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Shell ("CMD.EXE /c c:\IndexTrader\run_file\index_trader.bat")

一旦上面的.bat文件运行,我如何向excel环境打印一条消息,显示.bat文件已经执行。 如果我在.bat文件命令之后运行顺序代码(请参阅上面的代码),因为.bat文件是在excel环境之外执行的,因此即使.bat文件尚未完成,在该命令之后运行的任何顺序代码都将运行。 有没有一种方法可以输出一个消息或参数来显示.bat文件已经执行,然后只执行VBA中的任何顺序代码。在


Tags: 文件代码命令程序脚本cmd消息环境
1条回答
网友
1楼 · 发布于 2024-10-01 19:24:26

完全披露:曾经如此轻微地改编自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

您可以在示例中使用以下命令调用:

^{pr2}$

这种方法的另一个好处是可以捕获进程输出,从而将消息从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!"

相关问题 更多 >

    热门问题