Writing code into a Module via VBA & VBE

VenturSum

Board Regular
Joined
May 23, 2010
Messages
138
Team,

When I add a new worksheet, I must also copy to that sheet a command button. Next I need to add some code to the sheet's VBE object. And need some help here.

I've added the code to a string variable

Code:
sString = "Private Sub cboInsertText_Click()" & vbcrlf & _
          "Call InsertText" & vbcrlf & _
          "Sub End"

I've already changed the sheet's name. But I don't know what the sheet's "codename" is. So I need to address the VBE Object by the sheets' tab name.

Any Ideas??

John,
In Annapolis.
 
Last edited:

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
Hi John

Try this:

Code:
Sub AddWs_Code()
Dim wsh As Worksheet
Dim CodeM As CodeModule
Dim sString As String
 
sString = "Private Sub cboInsertText_Click()" & vbCrLf & _
          "Call InsertText" & vbCrLf & _
          "End Sub"
 
Set wsh = ActiveWorkbook.Worksheets.Add(After:=Sheets(Sheets.Count))
wsh.Name = "MyWorksheet"
 
Set CodeM = ActiveWorkbook.VBProject.VBComponents(wsh.CodeName).CodeModule
CodeM.InsertLines CodeM.CountOfLines + 1, sString
End Sub

Remark: I set the reference to "Microsoft Visual Basic for Applications Extensibility 5.3" to be able to use early binding.

If you don't set the reference, use

Code:
Dim CodeM As Object
 
Last edited:
Upvote 0
PGC,

Thank you very much for this post.
The client uses Excel 2000,
so I'll have to see which extension library is on his machine.

Most Gratefully,

John,
In Annapolis
 
Upvote 0

Forum statistics

Threads
1,222,900
Messages
6,168,926
Members
452,227
Latest member
sam1121

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top