Can VBA write VBA code into Modules or elsewhere

billbrunt

Board Regular
Joined
Jul 17, 2009
Messages
178
Hi -

I want to be able to write VBA which writes VBA code into the view code piece of a new worksheet. For example, I've got some code I'd like to include in

Code:
Private Sub Worksheet_Change(ByVal Target As Range)

The worksheet this would be incluided in would be dynamically created by some VBA code. So, once the worksheet is created, I'd then have my VBA routine write some VBA into the Worksheet_Change.

How can I do this?

- Bill
 

Some videos you may like

Excel Facts

Can you sort left to right?
To sort left-to-right, use the Sort dialog box. Click Options. Choose "Sort left to right"

Blade Hunter

Well-known Member
Joined
Mar 13, 2008
Messages
3,147
In the past I have had a blank sheet in my host macro which contains my Worksheet_Change macro. When you start your new workbook, copy the blank sheet from the host and it will take the macros with it.
 

usenethelp

New Member
Joined
Dec 3, 2009
Messages
33
You can do something like:

Sub AddCode()

Dim strCode As String

strCode = "Private Sub Worksheet_Change(ByVal Target As Range)" & vbCrLf
strCode = strCode & "msgbox target.value" & vbCrLf
strCode = strCode & "End Sub"

With ThisWorkbook.VBProject.VBComponents("Sheet1").CodeModule
.InsertLines .CountOfLines + 1, strCode
End With
End Sub
 

billbrunt

Board Regular
Joined
Jul 17, 2009
Messages
178
Mr. UseNetHelp --

Wow....perfect, just what I needed.

Thank you so much!

- Bill
 

Watch MrExcel Video

Forum statistics

Threads
1,122,216
Messages
5,594,886
Members
413,947
Latest member
gizmolucy

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
Top