从PowerShell运行PowerPoint宏

时间:2017-01-09 11:13:01

标签: vba powershell powerpoint

我有一个包含以下宏的PowerPoint:

Sub test()
    MsgBox "testing"
End Sub 

这样的PowerShell脚本:

$ppt = New-Object -ComObject PowerPoint.Application
$presentation = $ppt.Presentations.Open("test.pptm")
$ppt.Run("test")

但是运行宏只会给出:

Cannot find an overload for "Run" and the argument count: "1".
At line:1 char:1
+ $ppt.Run("test")
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

我得到同样的错误,例如$presentation.application.run("test")$ppt.Run("test.pptm!test")

相关:

Calling Excel macros from PowerShell with arguments

Passing a variant through COM object via PowerShell to run a macro in PowerPoint

文档建议Run应该将宏名称作为字符串作为其第一个参数,因此我无法看到我出错的地方。

OverloadDefinitions
-------------------
System.Object Run(string MacroName, [ref] Params System.Object[] safeArrayOfParams)
System.Object _Application.Run(string MacroName, [ref] Params System.Object[] safeArrayOfParams)

Application.Run Method (PowerPoint)

3 个答案:

答案 0 :(得分:0)

试试这个:

$ppt = New-Object -ComObject powerpoint.application
$presentation = $ppt.presentations.Open("test.pptm")
$ppt.Run("test", @())

答案 1 :(得分:0)

基于this post

$ppt = New-Object -ComObject PowerPoint.Application
$presentation = $ppt.Presentations.Open("test.pptm")
$presname = $presentation.Name
$VBScript = New-Object -ComObject "MSScriptControl.ScriptControl"
$VBscript.Language = "VBScript"
$VBscript.AddCode( 
@"
  Function RunVBA( app, functionName ) 
    RunVBA = app.Run( functionName, array() )
  End Function
"@
)

$VBscript.CodeObject.RunVBA( $ppt, "$presname!test" )

请注意,这仅适用于 Powershell x86,因为 ScriptControl 在 64 位环境中不可用。

答案 2 :(得分:0)

通过演示文稿访问 Application 对象对我有用:

$ppt = New-Object -ComObject PowerPoint.Application
$presentation = $ppt.Presentations.Open("test.pptm")
$presentation.Application.Run("test")