Num*_*er8 8 powershell vba microsoft-excel microsoft-excel-2010
我正在尝试从 Excel 中的宏调用 PowerShell 脚本。
我已经看到了一些例子:
retval = Shell("powershell ""C:\MyTest.ps1""", 1)
Run Code Online (Sandbox Code Playgroud)
但是,当我尝试使用它时:
Sub Connect_01()
Dim x
x = Shell(“powershell.exe ""\\corp\hdq\Path with spaces\PowerShell\Modules\macro01.ps1""", 1)
End Sub
Run Code Online (Sandbox Code Playgroud)
我收到一个编译器错误: Syntax error
如果我删除赋值,我会在第一对引号处收到错误:
Expected: list separator or )"
由于我对 VBA 没有太多经验,对 Shell() 命令也没有经验,因此将不胜感激。
nix*_*xda 15
有第二种方法可以做到这一点。它使用Windows Script Host 的Exec方法。
它有一个很大的优势,它可以从您的外部 PowerShell、命令行或您拥有的任何其他命令行工具读回值。因此,您可以在 Excel 和 Powershell 之间进行双向通信。
Sub RunAndGetCmd()
strCommand = "Powershell -File ""C:\path\to\My PS File.ps1"""
Set WshShell = CreateObject("WScript.Shell")
Set WshShellExec = WshShell.Exec(strCommand)
strOutput = WshShellExec.StdOut.ReadAll
Msgbox strOutput
End Sub
Run Code Online (Sandbox Code Playgroud)
命令的其他工作示例可能是
strCommand = "ping.exe 127.0.0.1"strCommand = "Powershell Echo Hello World"My PS File.ps1要演示的PowerShell 文件是echo "Hello World"
$x = 1 + 1
echo $x
Run Code Online (Sandbox Code Playgroud)
只要您echo的结果来自 PowerShell 文件或命令行工具,您就可以在 PowerShell 中执行所有复杂的操作。这意味着您写入StdOut(标准输出)。脚本完成后,Excel 读取所有值WshShellExec.StdOut.ReadAll
为确保带空格的路径从 Excel 正确传递到 PowerShell,请用四个双引号将路径括起来 "powershell -file ""C:\my path\"" "
Run方法相反,该Exec方法无法隐藏命令行窗口尝试使用这个而不是1. 不确定 1 来自哪里 -
Sub Connect_01()
Dim x as Variant
x = Shell("POWERSHELL.EXE " & "\\corp\hdq\Path with space\PowerShell\Modules\macro01.ps1", vbNormalFocus)
End Sub
Run Code Online (Sandbox Code Playgroud)
或者将其全部排除 -
Sub Connect_01()
Dim x
x = Shell("POWERSHELL.EXE " & "\\corp\hdq\Path with space\PowerShell\Modules\macro01.ps1")
End Sub
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
65880 次 |
| 最近记录: |