从VBA调用PowerShell命令不起作用,但可以

时间:2019-05-21 09:24:11

标签: excel vba powershell xlwings

当前,由于无法访问Windows的cmd,我无法使用xlwings。但是我可以访问PowerShell,因此我尝试更改xlwings特定的VBA代码,该代码调用cmd来调用PowerShell。

使用来自VBA的命令调用PowerShell时,它不起作用。如果我将完全相同的命令粘贴到PowerShell终端中,它将按预期工作。

我试图将VBA传递给PowerShell的(不起作用)命令与我手动粘贴到PowerShells终端中的(起作用)命令进行比较。但是它们看起来完全一样。

调用cmd的原始xlwings代码

RunCommand = PythonInterpreter & " -B -c ""import sys, os; sys.path[0:0]=os.path.normcase(os.path.expandvars(r'" & PYTHONPATH & "')).split(';'); " & PythonCommand & """ "

ExitCode = Wsh.Run("cmd.exe /C " & _
           DriveCommand & RunCommand & _
           """" & WORKBOOK_FULLNAME & """ ""from_xl""" & " " & _
           Chr(34) & Application.Path & "\" & Application.Name & Chr(34) & " " & _
           Chr(34) & Application.Hwnd & Chr(34) & _
           " 2> """ & LOG_FILE & """ ", _
           WindowStyle, WaitOnReturn)

还有我的稍加修改的版本

RunCommand = "C:\ProgramData\Anaconda3\pythonw.exe -B -c ""import sys, os; sys.path[0:0]=os.path.normcase(os.path.expandvars(r'" & PYTHONPATH & "')).split(';'); " & PythonCommand & """ "

ExitCode = Wsh.Run("Powershell.exe -ExecutionPolicy ByPass -NoExit " & _
           DriveCommand & RunCommand & _
           """" & WORKBOOK_FULLNAME & """ ""from_xl""" & " " & _
           Chr(34) & Application.Path & "\" & Application.Name & Chr(34) & " " & _
           Chr(34) & Application.Hwnd & Chr(34) & _
           " 2> """ & LOG_FILE & """ ", _
           WindowStyle, WaitOnReturn)

上面的代码产生的命令。直接粘贴到PowerShells终端时有效,而从VBA执行时无效:

C:\ProgramData\Anaconda3\pythonw.exe -B -c "import sys, os; sys.path[0:0]=os.path.normcase(os.path.expandvars(r'C:\Users\<placeholder>\test1;')).split(';'); import test1;test1.hello_xlwings()" "C:\Users\<placeholder>\test1\test1.xlsm" "from_xl" "C:\Program Files (x86)\Microsoft Office\Office16\Microsoft Excel" "788640" 2> "C:\Users\<placeholder>\AppData\Roaming\xlwings.log"

我希望有一个简单的“你好,世界!”单击与vba宏关联的按钮时,在特定的Excel单元格中单击。相反,我收到此错误:

At line:1 char:213
+ ... X0RNZ\test1;')).split(';'); import test1;test1.hello_xlwings() C:\Use ...
+                                                                  ~
An expression was expected after "(".
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpectedExpression

如果直接将命令粘贴到PowerShell终端中,则会得到预期的结果“ Hello,World!”。显示在我的特定Excel单元格中。

1 个答案:

答案 0 :(得分:0)

您缺少-Command参数。根据{{​​1}}所包含的内容,应在DriveCommand-Command之前添加DriveCommand

确保在PowerShell命令之间使用分号,并将命令指定为脚本块,例如:

RunCommand

运行powershell.exe -ExecutionPolicy ByPass -NoExit -Command { cd "c:\folder";c:\folder\run.exe "param1" "param2" } 以获得更多示例。