Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It is also possible (but maybe not advisable) to add code to a module programatically. Since VBA does not support reflection, this is the only type of "dynamic" coding there is in the language. This is useful in a pinch.</p> <p>See the snippet below. The <code>addCode</code> sub takes a standard module's name, a <code>Type</code>'s name, and an array containing the definition of the fields.</p> <p>It first tries to delete the existing <code>Type</code> with the same name, and then adds the new type definition in.</p> <pre><code>Sub TestAdd() Dim FieldArray() FieldArray = Array( _ "Firstname As String", _ "Lastname As String", _ "Username As String" _ ) AddCode "Module2", "Fields", FieldArray End Sub Sub AddCode(ModuleName As String, TypeName As String, FieldArray()) Dim StartLine As Long, EndLine As Long, StartColumn As Long, EndColumn As Long, _ CodeToInsert As String StartLine = 1: StartColumn = -1 EndLine = -1: EndColumn = -1 'Find the old type definition and remove it. With Application.VBE.ActiveVBProject.VBComponents(ModuleName).CodeModule 'Search for the start of the type definition If .Find("Public Type " &amp; TypeName, StartLine, StartColumn, EndLine, EndColumn, True) Then EndLine = EndLine + 1: StartColumn = -1: EndLine = -1: EndColumn = -1 'Found the start, now find the end of the type definition If .Find("End Type", EndLine, StartColumn, EndLine, EndColumn, True) Then .DeleteLines StartLine, (EndLine - StartLine) + 1 End If End If CodeToInsert = _ "Public Type " &amp; TypeName &amp; vbCrLf &amp; _ Join(FieldArray, vbCrLf) &amp; vbCrLf &amp; _ "End Type" .InsertLines StartLine, CodeToInsert End With End Sub </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload