vba create code dynamically

Hi

I am trying to make a user form where buttons and textbox are created on run time.

When the macro runs It searches for parts in the assembly and checks for a specific custom property and If true it creates a textbox with the filename and a toggle button next to It. The problem I am having Is that I need to add code for the toggle button on run time as well but I am stuck.

I have used the code below to insert lines of code but get an error: run-time 438 Object doesn`t support this property or method,

stops at the line ( With Myuserform.CodeModule)

I also have the reference Microsoft Visual Basic for Applications Extensibility 5,3 active

There Is a lot of examples on google ( mostly for excel ) but I cant get them to work with Solidworks .

Anyone knows what I am doing wrong here or guide me In the right way?

Dim MyUserform As Object

Dim X As Integer, MaxWidth As Long

Set MyUserform = UserForm1

    With MyUserform.CodeModule

        X = .CountOfLines

        .InsertLines X + 1, "Sub togglebutton1_Click()"

        .InsertLines X + 2, " msgbox "Hello World"

        .InsertLines X + 3, "End Sub"

    End With

SolidworksApi macros