Monday, August 29, 2011

Adding macros in a Word document on the fly

This one was troubeling me for AGES! I heard people saying it can't be done. But i knew deep down i could do it. But alas, a few things were missing. I could add the code as a module but not in the ThisDocument. I was getting depresed. What was the solution??? WHAT?

Well it was very simple! This line gave me the answer:
vbc = oDoc.VBProject.VBComponents(0)

where 0 is the ThisDocument with 1 the first module Module1! I was so happy! And to help all the other people with similar problems, i include the code i used. Hope this helps. (The code is not cleared up, needs a SaveAs command to save the document you just edited).

Also i would like to thank rxbagain from www.codeGuru.com that pointed me to the right direction. Thank you.

' ==========================================================================

Dim strFilenameToConvert As String
Dim procLine As Long
Dim oDoc As New Microsoft.Office.Interop.Word.Document
Dim vbProj As Microsoft.Vbe.Interop.VBProject
Dim vbc As Microsoft.Vbe.Interop.VBComponent
Dim vbcode As Microsoft.Vbe.Interop.CodeModule
Dim wordApp = New Microsoft.Office.Interop.Word.Application
Dim oModule As VBIDE.VBComponent

wordApp.Application.DisplayAlerts = False
strFilenameToConvert = "C:\hello.docx"
wordApp.WindowState = Word.WdWindowState.wdWindowStateNormal
wordApp.Visible = True
oDoc = wordApp.Documents.Open(strFilenameToConvert)

vbProj = oDoc.VBProject
vbc = oDoc.VBProject.VBComponents(0)
vbcode = vbc.CodeModule

' check if the procedure is already there
On Error Resume Next
procLine = vbcode.ProcBodyLine("Document_Open", vbext_ProcKind.vbext_pk_Proc)
On Error GoTo 0
' and add only if not found
If procLine = 0 Then
vbcode.AddFromString( _
"Private Sub Document_Open()" & vbCrLf & _
" MsgBox " & Chr(34) & "Macro added programmatically" & Chr(34) & vbCrLf & _
"End Sub")
End If

vbcode = Nothing
vbc = Nothing
vbProj = Nothing
oDoc = Nothing