Hi Jaydee
Programmatically changing VBA code in Word is possible but I advise caution.
Test your code thoroughly step by step. This sort of thing can easily run
amok and cause some serious headaches so make sure you BACK EVERYTHING UP!!!
The following should get you on the right track or at least give you some
ideas to experiment further. You need to set a reference to the Microsoft
Visual Basic Extensibility library.
I’ve left out any code dealing with opening up the templates which is
trivial in view of the rest. This code assumes you have a Template_1.dot file
already open and that it contains a routine called "MyTestSub()".
BTW, did I mention .. “BACK EVERYTHING UP!!!â€
Good luck, hope this helps.
Dennis
'------------------------------
Sub EditMySub()
Dim aMdl As VBComponent
Dim aPrj As VBProject
Dim lLin As Long
Dim strMyCode As String
Dim strSub2Edit As String
'Change this string to reflect the
'same name as the procedure you want to edit
strSub2Edit = "MyTestSub"
'strMyCode contains the code you want to insert
strMyCode = "MsgBox ""Hi I'm a piece of Code"""
Set aPrj = Documents("Template_1.dot").VBProject
'This will place your code into "Module1" of your
'project. The For Next loop is simply there to make
'sure the collection member exists.
For Each VBComponent In aPrj.VBComponents
If VBComponent.Name = "Module1" Then
Set aMdl = aPrj.VBComponents("Module1")
With aMdl.CodeModule
' Find the first line of the Sub
iLin = .ProcBodyLine(strSub2Edit, vbext_pk_Proc) + 1
' Insert your code
.InsertLines iLin, strMyCode
End With
Exit For
End If
Next VBComponent
'This example will add a whole new module and sub, putting
'the same code in it
Set aMdl = aPrj.VBComponents.Add(vbext_ct_StdModule)
aMdl.CodeModule.InsertLines 1, "Private Sub MyNewShinySub() " _
& vbCrLf & strMyCode & vbCrLf & "End Sub"
'Cleanup and exit
Set aMdl = Nothing
Set aPrj = Nothing
End Sub
'---------------------------------