Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Error Programmatically Creating Macro's in Word 2010 but works in Excel 1

Status
Not open for further replies.

JasonEnsor

Programmer
Sep 14, 2010
193
GB

Hey Guys,

I have some code that I have found (listed below) that works in Excel 2010 to programmatically create a new Module and Name it etc.... I am however struggling to get it to work in Word 2010. I have added the required reference to the "Visual Basic Extensibility" (although if I can get away without adding the reference it would be good). However in Word it kicks up an error on the following line
Code:
  Dim NewMod As Module
giving me a user defined type is not defined. Any ideas?

The code I am using is:
Code:
Option Explicit

Public Sub ModuleStart()
   ' Create the new module.
   Dim NewMod As Module
   Set NewMod = Modules.Add
   
   ' Get the module name.
   Dim ModName As String
   ModName = InputBox("Type the Module Name", "Name")
   NewMod.Name = ModName
   
   ' Get the new projects
   Dim MyProj As CodeModule
   Set MyProj = Application.VBE.VBProjects(1).VBComponents(ModName).CodeModule
   
   ' Open the file.
   MyProj.CodePane.Show
   
   ' Add the required option statement, module header, and opening Sub.
   MyProj.InsertLines 1, "Option Explicit" + vbCrLf + vbCrLf + _
      "' Module Name: " + ModName + vbCrLf + "' Author: " + _
      Application.UserName + vbCrLf + "' Date: " + CStr(DateTime.Now) + _
      vbCrLf + vbCrLf + "Public Sub " & CStr(ModName) & "()" + vbCrLf + vbCrLf + "End Sub"
End Sub

I am trying my best to extend my knowledge however resources online seem sparse, Ideally I would like to update some of my projects to VSTO in the future as I think that would solve a few of my previous user issues I've had in the past but again the resources just don't seem to be around.

Any help is as always appreciated.

J.
 
I'd try something like this:
Dim NewMod As VBComponent
Set NewMod = Application.VBE.VBProjects(1).VBComponents.Add(vbext_ct_StdModule)

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
BTW, don't give the same name for the module and the sub ...

Hope This Helps, PH.
FAQ219-2884
FAQ181-2886
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top