通过PowerShell通过COM对象传递变量以在PowerPoint中运行宏

时间:2016-02-23 14:19:39

标签: vba powershell powerpoint powerpoint-vba

尝试将标题串在一起足以构成挑战......

我正在尝试从PowerShell运行一些PowerPoint宏。我已经非常擅长从Powershell for Excel运行宏。当我在Excel上运行宏时,COM对象的Run()方法将采用各种参数,具体取决于宏是否有任何参数。但另一方面,PowerPoint Run()方法需要参数,我无法弄清楚如何传递它们。

我的宏期待一个字符串被传递,我已经大量搜索并且缩短了。我总是得到这个错误:

错误:

type must not be ByRef

我在PowerShell中整理了一个非常基本的PoC for PowerPoint:

代码:

# PowerPoint test
Add-type -AssemblyName office
$PowerPoint = New-Object -comobject PowerPoint.Application

$PowerPoint.Visible = [Microsoft.Office.Core.MsoTriState]::msoTrue

$presentation2 = $PowerPoint.Presentations.open("C:\macros.pptm")
$presentation = $PowerPoint.Presentations.open("C:\Test For Macros.pptx")

$PowerPoint.run("macros.pptm!IAM",[ref]"Feb")
$presentation.save()
$presentation.close()

$presentation2.close()
$PowerPoint.quit()

# extra clean up omitted

宏本身只是在框中移动一些文本,从PowerPoint运行时它可以正常工作。

要求:

我现在希望在多个文件和幻灯片中实现自动化。

Documentation on the PowerPoint COM object Run method,显示了两个参数的要求。

2 个答案:

答案 0 :(得分:4)

很好的问题,而不是像你说的那样在网上有很多例子。我设法将你的例子进一步删除,并成功地将一些文本传递给PowerPoint宏中的MsgBox,而没有真正改变你的内容。

文件PowerShellTest.pptm中的宏保存在C:\ Temp

Sub DisplayMessage(myText As String)
  MsgBox myText
End Sub

PowerShell脚本:

# PowerPoint test
Add-type -AssemblyName office
$PowerPoint = New-Object -comobject PowerPoint.Application

$PowerPoint.Visible = [Microsoft.Office.Core.MsoTriState]::msoTrue

$presentation = $PowerPoint.Presentations.open("C:\Temp\PowerShellTest.pptm")

$PowerPoint.run("PowerShellTest.pptm!DisplayMessage",[ref]"Feb")

您提供的Run方法文档链接提到可能包含模块名称,因此这也适用于我:

$PowerPoint.run("PowerShellTest.pptm!Module1.DisplayMessage",[ref]"Feb")

答案 1 :(得分:1)

也许尝试删除下面代码行中的[ref]或尝试将其更改为[val]

$PowerPoint.run("macros.pptm!IAM",[ref]"Feb")

所以:

$PowerPoint.run("macros.pptm!IAM","Feb")

或:

$PowerPoint.run("macros.pptm!IAM",[val]"Feb")

然后还要确保PowerPoint宏期望变量传递ByVal。例如:

Sub IAM(ByVal sMonthName As String)