Working with objects in the VBA Editor through the object model requires a reference to the Microsoft Office VBA Extensibility 5.3 object model which you can find in the COM tab of Project/Add References in Visual Studio.
I like to add an Imports statement to the top of the code so that I don't have to always write out the full namespace qualification:
Imports VBE = Microsoft.Vbe.Interop
An AutoOpen macro needs to be a "public" Sub
in a normal code module. Assuming you want to add a new code module to the document, use the VBComponents.Add
method and specify the enumeration type vbext_ct_StdModule
.
By default, the VBE will name the new module "Module#" - an incrementing number. If you ever need to programmatically address this module again (to see if it exists, for example) it would probably be better to assign a name to it.
Code as a string is added using the AddFromString
method.
If you're adding code to a document the possibility exists that the document is of type docx, meaning it cannot contain macro code. A document must have the extension docm in order to contain macro code. So you may need to use the SaveAs method on the document to change the file type and the name!
Private Sub InsVbaCode_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles InsVbaCode.Click
'Helper method to get current Word instance or, if none, start one
GetWordProcess()
Dim doc As Word.Document = WordApp.ActiveDocument
Dim vbModule As VBE.VBComponent = doc.VBProject.VBComponents.Add(VBE.vbext_ComponentType.vbext_ct_StdModule)
vbModule.Name = "basAddedCode"
vbModule.CodeModule.AddFromString( _
"Sub AutoOpen()" & vbLf & _
" MsgBox ""Document "" & ActiveDocument.FullName & "" has been opened successfully!""" & vbLf & _
"End Sub")
'doc.Save() or doc.SaveAs to change file type and/or name
End Sub