Inserting a module into a new workbook using VBA

北城以北 提交于 2020-12-16 03:09:43

问题


I've had a trawl around the net and can't seem to find a simple solution to this one so hopeing you can help.

I have a Macro at the moment which takes data from a .txt file and overwrites an excel file with the latest data every 3 minutes. It names the new file using the date and time of the overwrite.

What i would like is for the workbook with the 'create new workbook' macro to also add a new module into each new workbook as it is created, including a pre-written macro inside the module (The inserted module will include code to record who and when the workbook is opened and closed by so will be writing into a third workbook, but i can do that bit)

I'm hoping that all of this can be done with a second Sub!


回答1:


I'll get you started with adding a new module to a workbook, but can't possibly write everything for you.

We'll be using the VBA Extensibility library (VBE). It contains the definitions of the objects that make up the VBProject. So, before you start, make sure to add this reference:

Microsoft Visual Basic For Applications Extensibility 5.3

to your workbook. To do that, in the VBA editor go the the Tools menu and choose References. In that dialog, scroll down to and check the entry for Microsoft Visual Basic For Applications Extensibility 5.3. If you don't set this reference, you will receive a compiler error.

You also need to enable programmatic access to the VBA Project. To do that (in Excel 2010 -- similar steps for other versions), go to File > Options > Trust Center > Trust Center Settings... > Macro Settings and tick Trust access to the VBA project object model.

And now you're ready for the code:

Public Sub AddNewModule()

  Dim proj As VBIDE.VBProject
  Dim comp As VBIDE.VBComponent

  Set proj = ActiveWorkbook.VBProject
  Set comp = proj.VBComponents.Add(vbext_ct_StdModule)
  comp.Name = "MyNewModule"

  Set codeMod = comp.CodeModule

  With codeMod
    lineNum = .CountOfLines + 1
    .InsertLines lineNum, "Public Sub ANewSub()"
    lineNum = lineNum + 1
    .InsertLines lineNum, "  MsgBox " & """" & "I added a module!" & """"
    lineNum = lineNum + 1
    .InsertLines lineNum, "End Sub"
  End With

End Sub

This will add a new standard module, called "MyNewModule" to the active workbook and hardcode a little sub called "ANewSub" that, when run, simply shows a message box.

I trust and hope you can take this and build on it.



来源:https://stackoverflow.com/questions/24807623/inserting-a-module-into-a-new-workbook-using-vba

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!