简体   繁体   中英

Import macros programmatically in Word document

I am trying to automate the process of importing macros in Word documents, but I fail to load macros in any macro-enabled word document. It works just for the Normal.dotm

I want to create a new doc, and load the macro from a .bas file.

$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()

What am I doing wrong?

Use .SaveAs($docPath,0) where 0 is 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()

Or use extension .docm and .SaveAs($docPath,13) where 13 is 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM