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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With