问题
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