【发布时间】:2019-05-21 20:44:49
【问题描述】:
目前我无法使用 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"
我期待一个简单的“你好,世界!”单击与 vba 宏关联的按钮时,在特定的 Excel 单元格中。相反,我得到了这个错误:
在行:1 字符:213 + ... X0RNZ\test1;')).split(';');导入 test1;test1.hello_xlwings() C:\使用 ... + ~ “(”之后应该有一个表达式。 + CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException +fullyQualifiedErrorId:预期表达式如果我将命令直接粘贴到 PowerShell 终端中,我会得到预期的结果,“Hello, World!”显示在我的特定 Excel 单元格中。
【问题讨论】:
标签: excel vba powershell xlwings