Workbook Events Workout
- 03:44
Workout to demonstrate examples of workbook events.
Transcript
In this workout, we are required to write VBA code to add the text from the welcome sheet cell, A 2, in cell A 1 every time we create a new sheet.
Let's jump into Visual Basic Editor to write our event code.
We want to create a workbook event, an event that will trigger code to run at the workbook level.
And in order to do that, we double click this workbook from the Project Explorer and from the object work.
From the object dropdown, we select workbook and from the procedure dropdown.
This is the event that we wish our code to be triggered by and we wish our code to run every time a new sheet is inserted. So I'm going to select new sheet from that procedure dropdown menu.
Now, I don't need the code for an event that is triggered by a workbook opening, so I can delete that and I want to write my code just here.
This procedure will run whenever a new sheet is inserted and the SH parameter contains a reference to the newly created sheet. By Val specifies that an argument is passed to the procedure by value, so that the called procedure cannot change the value of a variable.
Here SH is the object variable ie; the worksheet object that is created.
Let's write code so that we can place a standard title in cell A 1 of every newly created sheet.
The newly created worksheet object we know is SH and within that worksheet object.
We wish to specify the range object A 1, and we wish that value property of range A1 to take the following value.
We wish it to take the value of whatever text appears On our welcome sheet from cell A 2, we specify the worksheet object and the range object on that worksheet.
And specifically we want cell A 1 in our newly created worksheet to take the value property from cell A 2 of the welcome sheet.
Let's go back into the front end of Excel and test our code in the front end of Excel.
We expect our procedure to be triggered by the event of inserting a new worksheet.
Let's go ahead and insert a new sheet.
A new sheet is inserted the code triggers and we can see cell A 1.
One of the newly inserted sheet contains the words VBA programming fundamentals from cell A 2 in our welcome sheet.