I’m presented with a puzzle. Where I work there are a huge amount of Word templates which all contains an autonew eventhandle which contains some errors. And this error lies within all templates. And I was wondering if there might be a way of scanning a directory for templates which contains this macro and change the macro code slightly?
Could this be possible?
Yes, you can do that. You can access the VBA project of any document using:
Your project must have a reference to “Microsoft Visual Basic for Applications Extensibility”.
To run the code, you must enable the “Trust Access to Visual Basic Project” option in Word, using
The
VBComponentscollection contains all the standard modules, class modules, forms and “document” modules that the project contains. If you Google it, you’ll find plenty of help on how to access/modify them.EDIT: OK, some more detail. This method will search all the
VbComponentsof a document looking for a method with the specified name, and perform a search/replace within the first one it finds.Note that this will only work with
SubandFunctionmethods, not propertyGet/Set/Letbecause I’m usingvbext_pk_Proc. It’s a PITA that you need to be explicit about this. Frankly, the whole API for theCodeModulecomponent seems almost designed to frustrate. For example, while theVbComponentobject has aFindmethod (which you’d think was a convenient way to find the text you’re looking for), it actually returnsTrueorFalse(!). Useful, I don’t think!The designers of this API must have had a really bad hangover when they did this.