Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

While generating hundreds of Office Excel spreadsheets with Office Access is certainly possible, it would be great to add macros to the generated workbooks.

I would like to add the functions to the object "ThisWorkbook" in the VBA project for each spreadsheet on generation. How would one go about doing this?

Thank you in advance!

share|improve this question
    
I'd do it by copying an existing workbook with the functions in it. If that doesn't work for you, please tell us a little more about your situation. –  Doug Glancy Jun 5 '13 at 3:48

1 Answer 1

up vote 0 down vote accepted

Under the assumption that the macro's in all generated workbooks are the same,

  • create a template containing all VBA code (and optionally constant text like headers, footers, print range definitions, etc. - i.e. "everything except data")
  • create any new workbook from the template
  • insert your data into the WB object
  • save as macro enabled worksheet (Excel 2007/2010)
  • close it

example

Sub CreateWB()
Dim WB As Workbook

    Set WB = Workbooks.Add("MacroTemp.xltm")   ' contains VBA, ActiveX, etc.
    WB.Worksheets("Sheet1").[A1] = "co-cooo!"  ' adding data
    WB.SaveAs "MyGenWB", xlOpenXMLWorkbookMacroEnabled
    WB.Close
End Sub

In Excel 2007/2010 do not forget to save the template as macro enabled template (*.xltm").

share|improve this answer
    
Thank you, this is great @MikeD. I hadn't thought of jamming it in a template. Solved all of my needs. –  user2454091 Jun 5 '13 at 22:38

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.