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