1
votes

I want to remove all vba-modules from an MS Word template using VBScript. I wrote the following script.


const wdDoNotSaveChanges = 0

WScript.Echo "starting Word..."
Dim oApplication, doc
Set oApplication = CreateObject("Word.Application")

WScript.Echo "opening template..."
oApplication.Documents.Open "path\to\test.dot"
Set doc = oApplication.ActiveDocument

Dim comp, components
Set components = oApplication.ActiveDocument.VBProject.VBComponents
For Each comp In components
    components.Remove comp
Next

WScript.Echo "exiting..."

doc.close wdDoNotSaveChanges
oApplication.Quit wdDoNotSaveChanges

When running similar code in a VBA-module in Word, that works, but when I run this VBScript, I get this error: test.vbs(14, 2) Microsoft VBScript runtime error: Invalid procedure call or argument

1
Why don't you remove it from within VBA? - Irwin M. Fletcher
Did you give permission to access the VBA project? This is done via a check box ("Trust access to the VBA project object model") under the macro security settings. - Dirk Vollmar
@irwin: because I want to do this from an Ant-script - NetForce1
@divo: Yes, I gave that permission, I actually use similar code to import and export vba-modules. - NetForce1

1 Answers

1
votes

It turns out that it is not possible to remove the VBComponent named "ThisDocument" (If you right click it in the IDE the remove option is not active). You can use something like:

For Each comp In components 
    If comp.Name <> "ThisDocument" Then
        components.Remove comp
    End If
Next