In Word 2003, if you need to know if a document contains any VBA code/macros in it, you can use the following function.
Function ContainsCode(ByVal Doc As Document) As Boolean
ContainsCode = False
Dim comp As Object
For Each comp In Doc.VBProject.VBComponents
If comp.CodeModule.CountOfLines > 0 Then
ContainsCode = True
Exit Function
End If
Next
End Function
To get the function to work correctly, you will need to change a security setting and enable the “Trust access to the VBA project object model” setting.
Once you’ve enabled that setting you can do lots of fun stuff within VBA – but I’ll cover that in some other posts one day.
Then just call the function with the document you want to check, such as:
If ContainsCode(ActiveDocument) then MsgBox “This document contains macros”
Life is much easier in Word 2007 and 2010. You can just use the HasVBProject property of the document. It returns TRUE if there is code in the document, otherwise it’s FALSE.
If ActiveDocument.HasVBProject then MsgBox “This document contains macros”
Too easy! Microsoft was even nice enough to add it to not only the Document object model, but also to the Workbook and Presentation objects, so it is also available in Excel and PowerPoint. Nice one – it’s about time there were some more consistencies between the object models in Office.
I like it when my code becomes redundant for a good reason.