如何在 VBA 中创建代码模块

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18499361/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 23:02:46  来源:igfitidea点击:

How can I create a Code Module in VBA

excel-vbavbaexcel

提问by user1283776

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.

但他们没有工作。我也用谷歌搜索过,但这似乎不是一个热门话题。

回答by Mathieu Guindon

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 AddFromFileif you have a .bas file you've exported and you want to load into a workbook.

AddFromFile如果您有一个已导出的 .bas 文件并且想要加载到工作簿中,您也可以这样做。