Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 152
  • Last Modified:

Add Word macro with VB

I have to open a existing Word Document adding a macro to it.

I am stuck with adding macro part. How can I do it thru' VB code.

Please help.
1 Solution
You'll need a reference to the Microsoft Visual Basic for Applications Extensibility.

This will add a module and put some code into it:
Sub CodeTest()
    Dim cMod As VBComponent, sCode As String
    Set cMod = ActiveDocument.VBProject.VBComponents.Add(vbext_ct_StdModule)
    sCode = "Public Sub HelloWorld" & vbCrLf & "  Msgbox ""Hello World""" & vbCrLf & "End Sub"
    cMod.CodeModule.InsertLines 1, sCode
    Set cMod = Nothing
End Sub

Replace ActiveDocument with the right Document-Object you're using.
This old question needs to be finalized -- accept an answer, split points, or get a refund.  For information on your options, please click here-> http:/help/closing.jsp#1 
Experts: Post your closing recommendations!  Who deserves points here?
sbattaAuthor Commented:
Steiner gets the points and please do close the question.

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now