Adding and Deleting VBA code using VBA:   Return to List

' Delete any prior code in this module
StandingCodeLines = ActiveDocument.VBProject.VBComponents("ThisDocument").CodeModule.CountOfLines
If StandingCodeLines > 0 Then
    ActiveDocument.VBProject.VBComponents("ThisDocument").CodeModule.DeleteLines 1, StandingCodeLines
End If

' Set up the string of code to Add (note that quotes must be doubled to be entered as string characters)
strN = strN & "Sub AutoOpen()" & vbCr
strN = strN & " MsgBox ""Hello World"", vbOKCancel, _" & vbCr
strN = strN & " "" Sample Message.""" & vbCr
strN = strN & "End Sub" & vbCr

' Add the module to "This Document"
ActiveDocument.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString strN



Note to Webmaster