簡體   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