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
 

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
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.
 
Upvote 0
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
 
Upvote 0

Forum statistics

Threads
1,214,826
Messages
6,121,793
Members
449,048
Latest member
greyangel23

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