在 Word 文档中以编程方式导入宏

Import macros programmatically in Word document

我正在尝试自动执行在 Word 文档中导入宏的过程,但我无法在任何启用宏的 word 文档中加载宏。它仅适用于 Normal.dotm

我想创建一个新文档,并从 .bas 文件加载宏。

$basPath = "C:\Files\macro.bas"
$docPath = "C:\Files\macro_document.doc"

$word = New-Object -ComObject "Word.Application"
$document = $word.documents.Add()
$document.SaveAs($docPath)

$document.VBProject.VBComponents.Import($basPath)

$document.Save()
$document.Close()
$word.Quit()

我做错了什么?

使用 .SaveAs($docPath,0) 其中 0 是 wdFormatDocument 97-2003

$basPath = "C:\Files\macro.bas"
$docPath = "C:\Files\macro_document.doc"

$word = New-Object -ComObject "Word.Application"
$document = $word.Documents.Add()
$document.VBProject.VBComponents.Import($basPath)
$document.SaveAs($docPath,0) # 0 = wdFormatDocument 97-2003
$document.Close()
$word.Quit()

或使用扩展名 .docm.SaveAs($docPath,13) 其中 13 是 wdFormatXMLDocumentMacroEnabled:

$basPath = "C:\Files\macro.bas"
$docPath = "C:\Files\macro_document.docm"

$word = New-Object -ComObject "Word.Application"
$document = $word.Documents.Add()
$document.VBProject.VBComponents.Import($basPath)
$document.SaveAs($docPath,13) # 13 = wdFormatXMLDocumentMacroEnabled
$document.Close()
$word.Quit()