Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a Code Module in VBA

Tags:

excel

vba

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.

like image 304
user1283776 Avatar asked Aug 28 '13 22:08

user1283776


People also ask

How do I create a VBA module?

Insert a VBA Module Next, right-click on the project (Excel File) in which you want to insert a module. After that, go to the Insert and click on the “Module”. Once you do that, you will instantly get a new module and can open its code window to write the code.

How do you create a module in Excel?

Press Alt+F11 to open the Visual Basic Editor (on the Mac, press FN+ALT+F11), and then click Insert > Module. A new module window appears on the right-hand side of the Visual Basic Editor.

What is module in VBA code?

Code Modules – The code modules are the most common place we store macros. The modules are located in the Modules folder within the workbook. Sheet Modules – Each sheet in the workbook has a sheet object in the Microsoft Excel Objects folder.


1 Answers

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.

like image 135
Mathieu Guindon Avatar answered Oct 20 '22 00:10

Mathieu Guindon