I'm wondering if there is a way to have a certain VBA code written by default in a Worksheet. So that if I create new Worksheets, the code will automatically be written in them. Is it possible or is it science fiction?
There is an event procedure called Workbook_NewSheet located in the Thisworkbook module. This is where you will have your code to create new code for the new worksheets. The Workbook_NewSheet event procedure automatically runs when you create a new worksheet.
What might be a little easier is to copy (then modify) an existing worksheet. If the existing worksheet already has event procedure code, it's copy will have the same code.
To expand on what Rorya has suggested, check out the Workbook_SheetChange event. If the code is identical with each worksheet, all you need to do is make sure that you qualify each range with Sh. For example:
Code:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
With Sh
If Not Intersect(Target, .Range("A1:B10")) Is Nothing Then
'stuff
End If
End With
End Sub
Note how I referenced .Range("A1:B10"), not Range("A1:B10")
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.