Add Word macro with VB

Posted on 2003-03-12
Medium Priority
Last Modified: 2010-05-01
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.
Question by:sbatta
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 11

Accepted Solution

Steiner earned 60 total points
ID: 8126183
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.

Expert Comment

ID: 8900190
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?

Author Comment

ID: 9478095
Steiner gets the points and please do close the question.

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction While answering a recent question (http://www.experts-exchange.com/Q_27402310.html) in the VB classic zone, I wrote some VB code in the (Office) VBA environment, rather than fire up my older PC.  I didn't post completely correct code o…
The debugging module of the VB 6 IDE can be accessed by way of the Debug menu item. That menu item can normally be found in the IDE's main menu line as shown in this picture.   There is also a companion Debug Toolbar that looks like the followin…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
Show developers how to use a criteria form to limit the data that appears on an Access report. It is a common requirement that users can specify the criteria for a report at runtime. The easiest way to accomplish this is using a criteria form that a…

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question