如何在VBA中创建代码模块

时间:2022-12-10 23:15:03

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

我想用VBA创建一个代码模块。当我已经有一个代码模块时,我知道我可以使用它来设置它:

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 个解决方案

#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.

如果您已导出.bas文件并且要加载到工作簿中,也可以使用AddFromFile。

#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.

如果您已导出.bas文件并且要加载到工作簿中,也可以使用AddFromFile。