How can I create a Code Module in VBA

2020-03-24 03:33发布

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.

1条回答
干净又极端
2楼-- · 2020-03-24 03:45

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.

查看更多
登录 后发表回答