Search notes:

VB Editor Object Model: CodeModule

The codeModule object represents the source code that is associated with a form, class or document and allows to change the source code programmatically.
In the immediate window, a reference to a code module might be found with an expression such as
application.VBE.activeVBProject.vbComponents("module10").codeModule

Properties

Properties of codeModule are
codePane
countOfDeclarationLines
countOflines The number of lines in the source code
lines
parent
procBodyLine(procName, procKind) returns the line number at which the sub, function or property get, set or let procedure begins. procType is one of vbext_pk_proc, vbext_pk_get, vbext_pk_let or vbext_pk_set
procCountLines
procOfLine(line, procKind) Returns the name of the procedure that «occupies» line number line. If line is larger than the number of lines in the code module, the function returns the name of the last function. See procBodyLine for procKind.
procStartLine(procName, procKind)
vbe

Methods

Methods of codeModule are
addFromFile Compare with vbComponents.import
addFromString Inserts a line at the current cursor position.
createEventProc createEventProc("click", "labelFoo") creates a procedure to catch the click event on the control labelFoo and returns the line number where the event procedure was inserted.
deleteLines deleteLines n deletes line n. deleteLines n, m deletes m lines starting at line n. Note that line numbers are one-based.
find
insertLines

Inserting lines

In order to append a line to the source code, insertLines needs to be used:
dim mdl as codeModule
set mdl = application.VBE.ActiveVBProject.VBComponents("module10").codeModule
mdl.insertLines cm.countOfLines + 1, "' This line was added at " & format(now, "yyyy-mm-dd hh:nn:ss")
Unfortunately, mdl looses the reference to the code module object after executing mdl.insertLines

Changing a line

The following sequence changes the text of the third line:
dim mdl as codeModule
set mdl = …
set cm = application.VBE.ActiveVBProject.VBComponents("module10").codeModule
cm.replaceLine 3, " ' This line was changed programmatically"

Delete entire code module

dim mdl as codeModule
set mdl = …

if mdl.countOfLines > 0 then
   mdl.deleteLines 1, mdl.countOfLines
end if
Alternatively, the if then can be omitted by making sure there is always at least one line in the source code:
mdl.insertLines 1, "'"
mdl.deleteLines 1, mdl.countOfLines

See also

A code module might be associated with multiple code panes.
This example demonstrates how the codeMOdule object is used to create a dynamic event handler for a hyperlink on a worksheet.
This example demonstrates how CodeModuld can be used to dynamically create a VBA module and insert a sub and call it with Excel's application.run() function.
vbComponent
The VB Editor object model

Index