繁体   English   中英

从VBA调用时,PowerShell命令不起作用,但其他方式有效

[英]PowerShell command doesn't work when called from VBA, but otherwise works

目前我无法使用xlwings,因为我无法访问Windows的cmd。 但我可以访问PowerShell,因此我尝试更改调用cmd的xlwings特定VBA代码来调用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"

我期待一个简单的“Hello,World!” 单击与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单元格中。

您缺少-Command参数。 根据DriveCommand包含的内容,您应该在DriveCommandRunCommand之前添加-Command

确保de PowerShell命令之间有分号,并将命令指定为scriptblock,例如:

powershell.exe -ExecutionPolicy ByPass -NoExit -Command { cd "c:\folder";c:\folder\run.exe "param1" "param2" }

运行powershell /? 更多例子。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM