在VBA中,我正在运行我编写的一个外部软件。我知道该软件运行良好。我可以从命令行运行它。但是,当我尝试使用WScript.Shell.Run执行它时,它返回1,并且永远不会运行。我什至不能说它完全可以执行软件。
这是VBA类的执行部分。
Public Function Execute() As Integer
Dim wsh As Object
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim exitCode As Integer: exitCode = -1
Set wsh = VBA.CreateObject("WScript.Shell")
'Run program with arguments and wait for the program to finish
If Me.PrinterType = 1 Then exitCode = wsh.Run(Me.Path & " /serial=" & Me.SerialNumber & " /position=" & Me.Location & "", windowStyle, waitOnReturn)
If Me.PrinterType = 2 Then exitCode = wsh.Run(Me.Path & " /boxid=" & Me.Location & " /version=" & Me.Version, windowStyle, waitOnReturn)
Execute = exitCode
End Function
完整执行字符串的示例:
C:.path.to。\ PrintLabel.exe / serial = EOSJ61110044 / position = 2
所以我不知道发生了什么。
我可以成功使用以下VBA Shell function:
If Me.PrinterType = 1 Then exitCode = Shell(Me.Path & " /serial=" & Me.SerialNumber & " /position=" & Me.Location, vbHide)
但是问题就变成了VBA在继续操作之前没有等待软件完成。因此,我需要继续尝试使WScript.Shell
工作。我想念什么?是否有需要启用的特定参考,我可能会丢失?
更新1:
尝试使用此方法来模仿此SO帖子,但仍然没有成功:
If Me.PrinterType = 1 Then fullExecutionString = Me.Path & " /serial=" & Me.SerialNumber & " /position=" & Me.Location
If Me.PrinterType = 2 Then fullExecutionString = Me.Path & " /boxid=" & Me.Location & " /version=" & Me.Version
wsh.Run fullExecutionString, windowStyle, waitOnReturn
更新2: 做了一个小的方法,可以在Windows cmd控制台中重复该过程。它可以(或多或少)使用相同的代码。我猜这与带有参数的命令路径字符串有关吗?
Private Sub Button2_Released()
Dim wsh As Object
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1
Dim exitCode As Integer: exitCode = 0
Set wsh = VBA.CreateObject("WScript.Shell")
exitCode = wsh.Run("C:\Windows\System32\cmd.exe", windowStyle, waitOnReturn)
End Sub
答案 0 :(得分:0)
回答我自己的问题:
经过大量调试后,我解决了带空格的路径导致此问题的问题。如果我直接输入以下内容(注意引号位置),则代码将成功运行:
exitCode = wsh.Run("""C:\path.to\PrintLabel.exe"" /serial=EOSJ61110044 /position=2", windowStyle, waitOnReturn)
所以最后我调整了Path
属性:
Public Property Let Path(ByVal NewValue As String)
actPath = Chr(34) & NewValue & Chr(34)
End Property
Public Property Get Path() As String
Path = actPath
End Property