Default code in a Worksheet

vlad4239

New Member
Joined
Mar 11, 2011
Messages
3
Hi,

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?

Thank you,
Vlad4239
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
Possible.

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.

This is a good tutorial on Event procedures.
http://www.cpearson.com/excel/Events.aspx

This is a good tutorial on how to add vba code at run time.
http://www.cpearson.com/excel/vbe.aspx
 
Upvote 0
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.
 
Upvote 0
If it is event code, you may also want to use the workbook-level equivalent as this fires for all sheets including newly added ones.
 
Upvote 0
Welcome to the forums!

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")
 
Upvote 0

Forum statistics

Threads
1,224,588
Messages
6,179,743
Members
452,940
Latest member
rootytrip

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