5

I want to create a code module with VBA. When I already have a code module I know that I can set it using:

Set cdmdl = wbk.VBProject.VBComponents(codeModuleName).CodeModule

But if the code module does not exist, how can I create it?

I've tried a few lines like:

Set cdmdl = new.wbk.VBProject.VBComponents(codeModuleName).CodeModule
Set cdmdl = create.wbk.VBProject.VBComponents(codeModuleName).CodeModule

But they haven't worked. I've also Googled, but this doesn't seem like a popular topic.

3
  • 1
    I want to update some Excel files. They already have their VBA code updated. But they don't have the buttons that activate said VBA scripts. Commented Aug 28, 2013 at 22:45
  • 1
    See this link cpearson.com/excel/vbe.aspx Commented Aug 28, 2013 at 22:46
  • 4
    Then shouldn't you want to just copy the buttons from the source worksheet to the destination? Commented Aug 28, 2013 at 22:47

1 Answer 1

6

This worked for me:

Public Function CreateModule(xlwb As Workbook) As VBComponent
    Dim module As VBComponent
    Set module = xlwb.VBProject.VBComponents.Add(vbext_ct_StdModule)
    module.Name = "MyModule"
    module.CodeModule.AddFromString "public sub test()" & vbNewLine & _
                                    "    'dosomething" & vbNewLine & _
                                    "end sub"
    Set CreateModule = module
End Function

You can also AddFromFile if you have a .bas file you've exported and you want to load into a workbook.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.