Workbook sheetchange excel vba

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Workbook.SheetChange event (Excel)

vbaxl10.chm503091

vbaxl10.chm503091

excel

Excel.Workbook.SheetChange

37e727d8-255c-ac23-45d8-13a8e7639991

05/29/2019

medium

Workbook.SheetChange event (Excel)

Occurs when cells in any worksheet are changed by the user or by an external link.

Syntax

expression.SheetChange (Sh, Target)

expression An expression that returns a Workbook object.

Parameters

Name Required/Optional Data type Description
Sh Required Object A Worksheet object that represents the sheet.
Target Required Range The changed range.

Remarks

This event doesn’t occur on chart sheets.

Example

This example runs when any worksheet is changed.

Private Sub Workbook_SheetChange(ByVal Sh As Object, _ 
 ByVal Source As Range) 
 ' runs when a sheet is changed 
End Sub

[!includeSupport and feedback]

In this tutorial you’ll learn how to capture events occur for any sheet in the active workbook. The event procedures for these events use at least one argument (Sh) which represents the effected sheet. Excel declares the Sh argument as an Object data type rather than a Worksheet data type. Because a workbook has several types of Sheet objects such as: Worksheet and Chart (also Dialog and Macro which are obsolete). You can use the TypeName function to determine the type of Sh object. For example, TypeName(Sh) function returns Worksheet if the sheet is a worksheet or returns Chart if it is a chart sheet.

Open a workbook, press Alt + F11 to open VBE, click ThisWorkbook in the Project window and then choose Workbook from the Object drop-down, the next drop-down displays a list of all workbook events, see following figure:
Workbook sheet events

  1. SheetActivate
  2. SheetDeactivate
  3. SheetBeforeDelete
  4. SheetBeforeDoubleClick
  5. SheetBeforeRightClick
  6. SheetCalculate
  7. SheetChange
  8. SheetSelectionChange
  9. SheetFollowHyperlink
  10. SheetLensGalleryRenderComplete
  11. SheetTableUpdate

Workbook_SheetActivate

Syntax: Workbook_SheetActivate(Sh)

The SheetActivate event occurs when a sheet is activated in the workbook. To listen this event Workbook_SheetActivate procedure is used. This procedure uses one argument Sh, which represents the sheet that was activated.

Workbook_SheetActivate Examples:

The following code is executed when any sheet in the workbook is activated. The code displays a message with the name of the activated sheet:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
 MsgBox Sh.Name
End Sub

The Sh argument is declared as an Object data type rather than a Worksheet data type because Excel has several types of Sheet objects. You can use the TypeName function to determine the sheet type. The following example displays a message with the type of the activated sheet:

Private Sub Workbook_SheetActivate(ByVal Sh As Object)
 MsgBox TypeName(Sh)
End Sub

The Workbook_SheetActivate event occurs for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Activate event procedure.

Workbook_SheetDeactivate

Syntax: Workbook_SheetDeactivate(Sh)

The SheetDeactivate event occurs when any sheet in the workbook is deactivated, such as when a different sheet in the workbook is activated. To listen this event Workbook_SheetDeactivate procedure is used. This procedure uses one argument Sh that stores the sheet object that is deactivated.

Workbook_SheetDeactivate Example:

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
 If Sh.Name = "Sheet1" Then
  MsgBox Sh.Name & " was deactivated"
 End If
End Sub

The Workbook_SheetDeactivate procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Deactivate event procedure.

Workbook_SheetBeforeDelete

Syntax: Workbook_SheetBeforeDelete(Sh)

The SheetBeforeDelete event occurs before a sheet is deleted in the workbook. To listen this event Workbook_SheetBeforeDelete procedure is used. This procedure uses one argument Sh, which represents the sheet to be deleted. The Workbook_SheetBeforeDelete procedure does not have a Cancel argument, so you can not cancel the delete operation.

Workbook_SheetBeforeDelete Example:

Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
 MsgBox "Deleting " & Sh.Name
End Sub

The Workbook_SheetBeforeDelete procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_BeforeDelete event procedure.

Workbook_SheetBeforeDoubleClick

Syntax: Workbook_SheetBeforeDoubleClick(Sh, Target, Cancel)

The SheetBeforeDoubleClick event occurs when a cell on any worksheet is about to be double-clicked. To listen this event Workbook_SheetBeforeDoubleClick procedure is used. This procedure uses three arguments:

  1. Sh
    Represent the sheet
  2. Target
    It is the Range object which represents the cell that was double-clicked.
  3. Cancel
    By default, double-clicking a cell puts it into edit mode. You can halt this default behavior by assigning the True value to the Cancel argument.

Workbook_SheetBeforeDoubleClick Example:

The following code writes BrainBell.com on the double-clicked cell if the cell is empty and clear the cell if it is not empty:

Private Sub Workbook_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
 Cancel = True
 If IsEmpty(Target) = True Then
  Target.Value = "BrainBell.com"
 Else
  Target.Clear
 End If
End Sub

The Workbook_SheetBeforeDoubleClick procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_BeforeDoubleClick event procedure.

Workbook_SheetBeforeRightClick

Syntax: Workbook_SheetBeforeRightClick(Sh, Target, Cancel)

The SheetBeforeRightClick occurs when the user right-clicks any worksheet in the active workbook. To listen this event Workbook_SheetBeforeRightClick procedure is used. This procedure has two arguments:

  1. Sh
    Represents the active sheet
  2. Cancel
    You can cancel the right-click behavior by assigning the True value to the Cancel argument.

Workbook_SheetBeforeRightClick Example:

The following code disables the right-click effect on Sheet1 of active workbook:

Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
 If Sh.Name = "Sheet1" Then
  Cancel = True
  MsgBox "Right-click is disabled for Sheet1"
 End If
End Sub

The Workbook_SheetBeforeRightClick procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_BeforeRightClick event procedure.

Workbook_SheetCalculate

Syntax: Workbook_SheetCalculate(Sh)

The SheetCalculate event occurs when any worksheet is recalculated or after any changed data is plotted on a chart. To listen this event Workbook_SheetCalculate procedure is used. This procedure has one argument Sh which represent the sheet that triggers the calculation.

Workbook_SheetCalculate(Sh) Example:

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
 MsgBox Sh.Name & " was recalculated"
End Sub

The Workbook_SheetCalculate procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Calculate event procedure.

Workbook_SheetChange

Syntax: Workbook_SheetChange(Sh, Target)

The SheetChange event occurs when the user changes any cell’s content on any worksheet in the active workbook. To listen this event Workbook_SheetChange procedure is used. This procedure has two arguments, Sh which represent the sheet that triggers the change and Target which represents the range that was changed.

Workbook_SheetChange Example:

Following code displays a message with the address of changed cell/range:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 If Not Sh.Name = "Sheet1" Then Exit Sub
 MsgBox Target.Address & " has changed"
End Sub

The Workbook_SheetChange procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Change event procedure.

Workbook_SheetSelectionChange

The SheetSelectionChange event occurs when a different cell is selected on any worksheet in the workbook. To listen this event the Workbook_SheetSelectionChange procedure is used. This procedure has two arguments, Sh represents the active sheet and Target represents the new selected range.

Workbook_SheetSelectionChange Example:

The following procedure highlights the each new cell selection:

Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
 Target.Interior.ColorIndex = 4
End Sub

The Workbook_SheetSelectionChange procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_SelectionChange event procedure.

Workbook_SheetFollowHyperlink

Syntax: Workbook_SheetFollowHyperlink(Sh, Target)

The SheetFollowHyperlink event occurs when you click any hyperlink in active workbook. To listen this event the Workbook_SheetFollowHyperlink procedure is used. This event has two arguments, Sh is the active worksheet and Target is the hyperlink.

Workbook_SheetFollowHyperlink Example:

Following code displays a message when you click on a link:

Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
 MsgBox Target.Address
End Sub

The Workbook_SheetFollowHyperlink procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_FollowHyperlink event procedure.

Workbook_SheetLensGalleryRenderComplete

Syntax: Workbook_SheetLensGalleryRenderComplete(Sh)

The SheetLensGalleryRenderComplete event occurs when the user selects the Quick Analysis tool. To listen this event the Workbook_SheetLensGalleryRenderComplete procedure is used. This procedure has one argument Sh which represents the active worksheet.

Workbook_SheetLensGalleryRenderComplete Example:

Private Sub Workbook_SheetLensGalleryRenderComplete(ByVal Sh As Object)
 MsgBox "you've selected the Quick Analysis tool on " & Sh.Name
End Sub

The Workbook_SheetLensGalleryRenderComplete procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_LensGalleryRenderComplete event procedure.

Workbook_SheetTableUpdate

Syntax: Workbook_SheetTableUpdate(Sh, Target)

The SheetTableUpdate event occurs after a query table connected to a data model is updated. To listen this event Workbook_SheetTableUpdate procedure is used. This procedure has two arguments: Sh argument is the sheet with the query table and Target argument is the query table that was updated.

Workbook_SheetTableUpdate Example:

Following code displays a message with the table and sheet names when a query table gets update:

Private Sub Workbook_SheetTableUpdate(ByVal Sh As Object, ByVal Target As TableObject)
 MsgBox Target.ListObject.Name & " updated on " & Sh.Name
End Sub

For more information, learn how to create a query table / data model. The above code is executed when a query table updated on any sheet in the workbook. To listen this event for a specific worksheet, use Worksheet_TableUpdate procedure in the code module for that worksheet.

by updated Sep 04, 2020

You may want to run your macro/VBA snippet when a specific workbook is selected, A sheet in the workbook is selected, cell changes its value, when a double click happens, when a sheet is added, etc. In all these cases we use Workbook Event Handler.  The Event Handler helps us run VBA code whenever a certain event occurs.

In this article, we will learn briefly about each Workbook Event Handler.

What is a Workbook Event Handler?

A workbook event handler is a subroutine that is local to a workbook. These code work only on the components of a workbook. That are the workbook itself, it’s sheets and ranges. 

Where to write Workbook Event Handler Code?

The workbook events are written in the workbook object only. If you write a workbook event in some normal module, there will be no error but they will just not work.

To write in the workbook object. Double click on it or right-click and click on the view code. The code writing area will be shown.

How to write code for a specific event in the workbook?

Now when you are in the editing mode, in the top-left corner dropdown menu, you will see general. Click on the drop-down and select the workbook. In the top-right corner dropdown, all events will show. Choose whichever you need and a skeletal code for that event will be written for you.

Each event has a fixed procedure name. These are the reserved subroutine names that start with workbook_. You can’t use them for other subroutines
(you can, but they will be normal subroutines).

Important: Each subroutine from that list will run on the specified event.

One type of workbook event procedure can be written only once on one workbook. If you write two same event handling procedures in one workbook, it will result in an error and none of them will be executed. Of course, the error will be ambiguous subroutines.

Let’s learn briefly about each of the events.
1. The Workbook_SheetChange (ByVal Sh As Object, ByVal Target As Range) Event
 

This event triggers when we make any change to containing worksheets (formatting excluded). If you want to do something if any change made in any sheet then the code will be:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
  'do something 
  Msgbox "done something"
End Sub

The «Sh» is always the active sheet.  The «Target» is the Active cell always.

Another example: You may want to put date and time in Cel,prl B1 if A1 changes. In that case, we use the workbook_sheetchange event. The code would look like this:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
 If Target.Address = "$A$1" Then
  Range("B1").Value2 = Format(Now(), "hh:mm:ss")
 End If
End Sub

This will target only the cell A1 on every sheet since we have not specified the «sh» object.

2. The Workbook_Activate() Event
 

This event is triggered when the event code containing workbook activates. The skeletal code for this event is:

Private Sub Workbook_Activate()

End Sub

A simple example is showing the workbook name when it gets selected.

Private Sub Workbook_Activate()

  MsgBox "You are on workbook " & Activeworkbook.Name

End Sub

As soon as you will come on the workbook that contains this code, the event will run and will be shown a message that «You are on workbook name» (sheet2 is in my case).
3. The Workbook_Open() Event
 

This one of the most asked question that how to run a macro as soon as the workbook opens. This is the answer. This workbook event is runs as soon as the workbook is opened. Unlike Workbook_Activate() this code runs only once, not when every time it is activated.

Private Sub Workbook_Open()
'your code
'
End Sub

The below example Workbook_Open event will simply pop up a welcome message, when you open the code containing workbook.

Private Sub Workbook_Open()
  MsgBox "Welcome to the Master File"
End Sub

4. The Workbook_Deactivate() Event
 

This event triggers when leaving the code containing workbook. In other words, if you want to do something, like hiding sheets or anything when you switch workbook, use this VBA event. The syntax is:

Private Sub Workbook_Deactivate()
'your code
'
End Sub

The below example Workbook_Deativate event will simply pop up a message that you have left the master sheet, when you will leave this sheet.

Private Sub Workbook_Deactivate()
  MsgBox "You Left The Master Sheet"
End Sub

5. The Workbook_BeforeClose() Event
 

This event triggers when you confirm the deletion of the VBA event containing sheet. The syntax is simple:

Private Sub Workbook_BeforeClose(Cancel as Boolean)

End Sub

The Cancel can be set to true if you want to keep the workbook open.
The below code will ask you if you want to save the content of the about-to -close workbook.

Private Sub Workbook_BeforeClose(Cancel as Boolean)
    ans = MsgBox("Do you want to save the content of this workbook?", vbYesNo)
    If ans = True Then
    thisworkbook.save
 End If
End Sub

6. The Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Event
 

This event triggers when before the workbook is saved. The syntax is simple:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

End Sub

SaveAsUI is set True if there is a change in the workbook (not in VBA).

The Cancel can be set to true if you want to keep the workbook unsaved.

The below code will ask you if you want to save the content of the about-to -save workbook.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean,Cancel as Boolean)
    ans = MsgBox("Do you really want to save the content of this workbook?", vbYesNo)
    If ans = False Then
    Cancel = True
 End If
End Sub

7. The Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Event
 

This event triggers when before the workbook is saved. The syntax is simple:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

End Sub

SaveAsUI is set True if there is a change in the workbook (not in VBA).

The Cancel can be set to true if you want to keep the workbook unsaved.

The below code will ask you if you want to save the content of the about-to -save workbook.

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean,Cancel as Boolean)
    ans = MsgBox("Do you really want to save the content of this workbook?", vbYesNo)
    If ans = False Then
    Cancel = True
 End If
End Sub

8. The Workbook_NewSheet(ByVal Sh As Object) Event
 

This event fires when you add a new sheet to the workbook. The syntax is simple:

Private Sub Workbook_NewSheet(ByVal Sh As Object)

End Sub

The Sh is the sheet object. The type is actually is an core object so that if we add a chart sheet, a macro sheet or a dialog sheet, the event still works.

The below code will add and show the name of the sheet that is newly added.

Private Sub Workbook_NewSheet(ByVal Sh As Object)
 MsgBox "You added a new sheet. " & Sh.Name
End Sub

The are many more events of the workbook object. We can’t discuss them all here. If you want to know about some specific event then ask in the comments section below. I hope I was able to explain the basics of the workbook events in this article. Let me know if it helped you in the comments section below.
Related Articles:

Using Worksheet Change Event To Run Macro When any Change is Made | So to run your macro whenever the sheet updates, we use the Worksheet Events of VBA.

Run Macro If Any Change Made on Sheet in Specified Range | To run your macro code when the value in a specified range changes, use this VBA code. It detects any change made in the specified range and will fire the event.

Simplest VBA Code to Highlight Current Row and Column Using | Use this small VBA snippet to highlight the current row and column of the sheet.

Popular Articles:

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make your work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets. 

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific value. Countif function is essential to prepare your dashboard.

How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

Содержание

  1. VBA-Урок 11.1. События рабочей книги (Workbook Events)
  2. Workbook_Open (Открытие книги)
  3. Workbook_BeforeClose (Событие перед закрытием книги)
  4. Workbook_BeforeSave (Событие перед сохранением книги)
  5. Workbook_BeforePrint (Событие перед печатью книги)
  6. Workbook_AfterSave (Событие после сохранения книги)
  7. Workbook_SheetActivate (Событие переключения рабочего листа)
  8. Workbook_SheetBeforeDoubleClick (Событие двойного щелчка по ячейке)
  9. Workbook_SheetBeforeRightClick (Событие перед правым кликом)
  10. Workbook_SheetChange (Событие изменения содержания листа)
  11. Workbook_SheetCalculate (Событие пересчете листа)
  12. Workbook_SheetSelectionChange (Событие изменения выбранного диапазона ячеек)
  13. Workbook_NewSheet (Событие добавления нового листа)
  14. Workbook_SheetFollowHyperlink (Событие нажатия на ссылку)
  15. Workbook sheetchange excel vba
  16. Workbook Sheet Events
  17. Workbook_SheetActivate
  18. Workbook_SheetDeactivate
  19. Workbook_SheetBeforeDelete
  20. Workbook_SheetBeforeDoubleClick
  21. Workbook_SheetBeforeRightClick
  22. Workbook_SheetCalculate
  23. Workbook_SheetChange
  24. Workbook_SheetSelectionChange
  25. Workbook_SheetFollowHyperlink
  26. Workbook_SheetLensGalleryRenderComplete
  27. Workbook_SheetTableUpdate
  28. How To Use Workbook Events in VBA
  29. What is a Workbook Event Handler?

VBA-Урок 11.1. События рабочей книги (Workbook Events)

Мы можем иметь события рабочей книги (например, открытие, закрытие и т.д.), которые могут быть триггерами (переключателями) для VBA кода.

Workbook_Open (Открытие книги)

Чтобы выполнить инструкции, когда открывается рабочая книга, идем к ThisWorkbook и выбираем Workbook :

Событие Workbook_Open будет добавлено по умолчанию и будет действовать во время открытия книги:

Например, если мы добавим следующую инструкцию, тогда диалоговое окно будет отображено при открытии книги:

Workbook_BeforeClose (Событие перед закрытием книги)

Чтобы выполнить инструкции перед самым закрытием книги, выберите BeforeClose

Закрытие книги может быть отменено, если присвоить значение True к переменной «Cancel».

Ниже приведен пример, в котором пользователя спрашивают подтверждение на закрытие рабочей книги:

Workbook_BeforeSave (Событие перед сохранением книги)

Это событие возникает сразу перед самым сохранением рабочей книги:

Сохранение файла может быть отменено присвоением значения True к переменной «Cancel».

Workbook_BeforePrint (Событие перед печатью книги)

Это событие возникает перед самой печатью рабочей книги:

Печать файла может быть отменена присвоением значения True к переменной «Cancel».

Workbook_AfterSave (Событие после сохранения книги)

Это событие возникает сразу после сохранением рабочей книги:

Workbook_SheetActivate (Событие переключения рабочего листа)

Это событие возникает каждый раз, когда вы переключаетесь между листами рабочей книги:

В этом примере, название активированного листа отображается в диалоговом окне

Workbook_SheetBeforeDoubleClick (Событие двойного щелчка по ячейке)

Это событие возникает при двойном щелчке на ячейке рабочего листа

Например, мы можем использовать это событие, чтобы добавить цвет заливки ячейки, в зависимости от выбранного листа:

Workbook_SheetBeforeRightClick (Событие перед правым кликом)

Это событие возникает перед самым кликом правой кнопки мыши

Workbook_SheetChange (Событие изменения содержания листа)

Это событие возникает каждый раз, когда меняется содержание рабочего листа

Workbook_SheetCalculate (Событие пересчете листа)

Это событие возникает каждый раз, когда рассчитываются или пересчитываются данные на рабочем листе:

Workbook_SheetSelectionChange (Событие изменения выбранного диапазона ячеек)

Это событие возникает каждый раз, когда меняется содержание выбранного диапазона ячеек на расчетном листе

В этом примере, изменяется цвет заливки, если ячейка А1 пуста

Workbook_NewSheet (Событие добавления нового листа)

Это событие возникает каждый раз, когда добавляется новый лист в рабочую книгу:

Workbook_SheetFollowHyperlink (Событие нажатия на ссылку)

Это событие возникает при нажатии на ссылку (гипертекст):

Источник

Workbook sheetchange excel vba

Активация окна. Вызывается в момент активации книги. Этот момент наступает в тот момент, когда из другой активной книги вы переходите к той, в которой обрабатывается событие. Например, при переключении книги в меню «Окно».

Закрытие окна. Вызывается перед закрытием книги:

Деактивация книги. Вызывается в момент перехода к другой книге:

Активация листа. Вызывается в момент смены листа:

Деактивация листа. Вызывается в момент смены листа для того листа, с которого уходят:

Смена ячейки. Вызывается в момент смены диапазона или при редактировании ячейки:

Пересчет данных. Вызываться при пересчете данных, обычно пересчет связан с редактирование данных, поэтому ранее вызывается SheetChange практически всегда за исключением ручного пересчета.

Переход к ячейке. Вызывается при переходе от одной ячейки к другой:

Разрешение на печать. Вызывается при выборе меню «Печать»:

Разрешение на сохранение. Вызываеться перед сохранением документа:

Создание нового листа. Вызывается в момент создания нового листа. Обычно ведет за собой целую цепочку событий — Workbook_NewSheet, Workbook_SheetDeactivate, Workbook_SheetActivate:

Изменение размера листа. Вызывается в момент изменения размера листа:

Активизация окна. Вызывается в момент активизации окна книги, например, при переключении на книгу:

Щелчок правой кнопкой. Вызывается по нажатию правой кнопки мыши:

Выводы. Часть событий связана в цепочки. То есть, например, событие Activate для одного объекта это событие Deactivate для другого объекта. Это работает для Окон, Книг и Листов. Часть событий вызывают за собой следующие события, например, ввод данных приведет к пересчету листа. Или вставка нового листа к событиям активизации. Знание событий может помочь в решении нетривиальных вопросов. Вот так можно запретить печать книги.

Источник

Workbook Sheet Events

In this tutorial you’ll learn how to capture events occur for any sheet in the active workbook. The event procedures for these events use at least one argument (Sh) which represents the effected sheet. Excel declares the Sh argument as an Object data type rather than a Worksheet data type. Because a workbook has several types of Sheet objects such as: Worksheet and Chart (also Dialog and Macro which are obsolete). You can use the TypeName function to determine the type of Sh object. For example, TypeName(Sh) function returns Worksheet if the sheet is a worksheet or returns Chart if it is a chart sheet.

Open a workbook, press Alt + F11 to open VBE, click ThisWorkbook in the Project window and then choose Workbook from the Object drop-down, the next drop-down displays a list of all workbook events, see following figure:

Workbook_SheetActivate

Syntax: Workbook_SheetActivate(Sh)

The SheetActivate event occurs when a sheet is activated in the workbook. To listen this event Workbook_SheetActivate procedure is used. This procedure uses one argument Sh , which represents the sheet that was activated.

Workbook_SheetActivate Examples:

The following code is executed when any sheet in the workbook is activated. The code displays a message with the name of the activated sheet:

The Sh argument is declared as an Object data type rather than a Worksheet data type because Excel has several types of Sheet objects. You can use the TypeName function to determine the sheet type. The following example displays a message with the type of the activated sheet:

The Workbook_SheetActivate event occurs for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Activate event procedure.

Workbook_SheetDeactivate

Syntax: Workbook_SheetDeactivate(Sh)

The SheetDeactivate event occurs when any sheet in the workbook is deactivated, such as when a different sheet in the workbook is activated. To listen this event Workbook_SheetDeactivate procedure is used. This procedure uses one argument Sh that stores the sheet object that is deactivated.

Workbook_SheetDeactivate Example:

The Workbook_SheetDeactivate procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Deactivate event procedure.

Workbook_SheetBeforeDelete

Syntax: Workbook_SheetBeforeDelete(Sh)

The SheetBeforeDelete event occurs before a sheet is deleted in the workbook. To listen this event Workbook_SheetBeforeDelete procedure is used. This procedure uses one argument Sh , which represents the sheet to be deleted. The Workbook_SheetBeforeDelete procedure does not have a Cancel argument, so you can not cancel the delete operation.

Workbook_SheetBeforeDelete Example:

The Workbook_SheetBeforeDelete procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_BeforeDelete event procedure.

Workbook_SheetBeforeDoubleClick

Syntax: Workbook_SheetBeforeDoubleClick(Sh, Target, Cancel)

The SheetBeforeDoubleClick event occurs when a cell on any worksheet is about to be double-clicked. To listen this event Workbook_SheetBeforeDoubleClick procedure is used. This procedure uses three arguments:

  1. Sh
    Represent the sheet
  2. Target
    It is the Range object which represents the cell that was double-clicked.
  3. Cancel
    By default, double-clicking a cell puts it into edit mode. You can halt this default behavior by assigning the True value to the Cancel argument.

Workbook_SheetBeforeDoubleClick Example:

The following code writes BrainBell.com on the double-clicked cell if the cell is empty and clear the cell if it is not empty:

The Workbook_SheetBeforeDoubleClick procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_BeforeDoubleClick event procedure.

Workbook_SheetBeforeRightClick

Syntax: Workbook_SheetBeforeRightClick(Sh, Target, Cancel)

The SheetBeforeRightClick occurs when the user right-clicks any worksheet in the active workbook. To listen this event Workbook_SheetBeforeRightClick procedure is used. This procedure has two arguments:

  1. Sh
    Represents the active sheet
  2. Cancel
    You can cancel the right-click behavior by assigning the True value to the Cancel argument.

Workbook_SheetBeforeRightClick Example:

The following code disables the right-click effect on Sheet1 of active workbook:

The Workbook_SheetBeforeRightClick procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_BeforeRightClick event procedure.

Workbook_SheetCalculate

Syntax: Workbook_SheetCalculate(Sh)

The SheetCalculate event occurs when any worksheet is recalculated or after any changed data is plotted on a chart. To listen this event Workbook_SheetCalculate procedure is used. This procedure has one argument Sh which represent the sheet that triggers the calculation.

Workbook_SheetCalculate(Sh) Example:

The Workbook_SheetCalculate procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Calculate event procedure.

Workbook_SheetChange

Syntax: Workbook_SheetChange(Sh, Target)

The SheetChange event occurs when the user changes any cell’s content on any worksheet in the active workbook. To listen this event Workbook_SheetChange procedure is used. This procedure has two arguments, Sh which represent the sheet that triggers the change and Target which represents the range that was changed.

Workbook_SheetChange Example:

Following code displays a message with the address of changed cell/range:

The Workbook_SheetChange procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_Change event procedure.

Workbook_SheetSelectionChange

The SheetSelectionChange event occurs when a different cell is selected on any worksheet in the workbook. To listen this event the Workbook_SheetSelectionChange procedure is used. This procedure has two arguments, Sh represents the active sheet and Target represents the new selected range.

Workbook_SheetSelectionChange Example:

The following procedure highlights the each new cell selection:

The Workbook_SheetSelectionChange procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_SelectionChange event procedure.

Workbook_SheetFollowHyperlink

Syntax: Workbook_SheetFollowHyperlink(Sh, Target)

The SheetFollowHyperlink event occurs when you click any hyperlink in active workbook. To listen this event the Workbook_SheetFollowHyperlink procedure is used. This event has two arguments, Sh is the active worksheet and Target is the hyperlink.

Workbook_SheetFollowHyperlink Example:

Following code displays a message when you click on a link:

The Workbook_SheetFollowHyperlink procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_FollowHyperlink event procedure.

Workbook_SheetLensGalleryRenderComplete

Syntax: Workbook_SheetLensGalleryRenderComplete(Sh)

The SheetLensGalleryRenderComplete event occurs when the user selects the Quick Analysis tool. To listen this event the Workbook_SheetLensGalleryRenderComplete procedure is used. This procedure has one argument Sh which represents the active worksheet.

Workbook_SheetLensGalleryRenderComplete Example:

The Workbook_SheetLensGalleryRenderComplete procedure executes for all worksheets in the workbook, if you want to capture the event for a specific worksheet, use Worksheet_LensGalleryRenderComplete event procedure.

Workbook_SheetTableUpdate

Syntax: Workbook_SheetTableUpdate(Sh, Target)

The SheetTableUpdate event occurs after a query table connected to a data model is updated. To listen this event Workbook_SheetTableUpdate procedure is used. This procedure has two arguments: Sh argument is the sheet with the query table and Target argument is the query table that was updated.

Workbook_SheetTableUpdate Example:

Following code displays a message with the table and sheet names when a query table gets update:

For more information, learn how to create a query table / data model. The above code is executed when a query table updated on any sheet in the workbook. To listen this event for a specific worksheet, use Worksheet_TableUpdate procedure in the code module for that worksheet.

Источник

How To Use Workbook Events in VBA

You may want to run your macro/VBA snippet when a specific workbook is selected, A sheet in the workbook is selected, cell changes its value, when a double click happens, when a sheet is added, etc. In all these cases we use Workbook Event Handler. The Event Handler helps us run VBA code whenever a certain event occurs.

In this article, we will learn briefly about each Workbook Event Handler.

What is a Workbook Event Handler?

A workbook event handler is a subroutine that is local to a workbook. These code work only on the components of a workbook. That are the workbook itself, it’s sheets and ranges.

Where to write Workbook Event Handler Code?

The workbook events are written in the workbook object only. If you write a workbook event in some normal module, there will be no error but they will just not work.

To write in the workbook object. Double click on it or right-click and click on the view code. The code writing area will be shown.

How to write code for a specific event in the workbook?

Now when you are in the editing mode, in the top-left corner dropdown menu, you will see general. Click on the drop-down and select the workbook. In the top-right corner dropdown, all events will show. Choose whichever you need and a skeletal code for that event will be written for you.

Each event has a fixed procedure name. These are the reserved subroutine names that start with workbook_. You can’t use them for other subroutines
(you can, but they will be normal subroutines).

Important: Each subroutine from that list will run on the specified event.

One type of workbook event procedure can be written only once on one workbook. If you write two same event handling procedures in one workbook, it will result in an error and none of them will be executed. Of course, the error will be ambiguous subroutines.

Let’s learn briefly about each of the events.
1. The Workbook_SheetChange (ByVal Sh As Object, ByVal Target As Range) Event

This event triggers when we make any change to containing worksheets (formatting excluded). If you want to do something if any change made in any sheet then the code will be:

The «Sh» is always the active sheet. The «Target» is the Active cell always.

Another example: You may want to put date and time in Cel,prl B1 if A1 changes. In that case, we use the workbook_sheetchange event. The code would look like this:

This will target only the cell A1 on every sheet since we have not specified the «sh» object.

2. The Workbook_Activate() Event

This event is triggered when the event code containing workbook activates. The skeletal code for this event is:

A simple example is showing the workbook name when it gets selected.

As soon as you will come on the workbook that contains this code, the event will run and will be shown a message that «You are on workbook name» (sheet2 is in my case).
3. The Workbook_Open() Event

This one of the most asked question that how to run a macro as soon as the workbook opens. This is the answer. This workbook event is runs as soon as the workbook is opened. Unlike Workbook_Activate() this code runs only once, not when every time it is activated.

The below example Workbook_Open event will simply pop up a welcome message, when you open the code containing workbook.

4. The Workbook_Deactivate() Event

This event triggers when leaving the code containing workbook. In other words, if you want to do something, like hiding sheets or anything when you switch workbook, use this VBA event. The syntax is:

The below example Workbook_Deativate event will simply pop up a message that you have left the master sheet, when you will leave this sheet.

5. The Workbook_BeforeClose() Event

This event triggers when you confirm the deletion of the VBA event containing sheet. The syntax is simple:

The Cancel can be set to true if you want to keep the workbook open.
The below code will ask you if you want to save the content of the about-to -close workbook.

6. The Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Event

This event triggers when before the workbook is saved. The syntax is simple:

SaveAsUI is set True if there is a change in the workbook (not in VBA).

The Cancel can be set to true if you want to keep the workbook unsaved.

The below code will ask you if you want to save the content of the about-to -save workbook.

7. The Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean) Event

This event triggers when before the workbook is saved. The syntax is simple:

SaveAsUI is set True if there is a change in the workbook (not in VBA).

The Cancel can be set to true if you want to keep the workbook unsaved.

The below code will ask you if you want to save the content of the about-to -save workbook.

8. The Workbook_NewSheet(ByVal Sh As Object) Event

This event fires when you add a new sheet to the workbook. The syntax is simple:

The Sh is the sheet object. The type is actually is an core object so that if we add a chart sheet, a macro sheet or a dialog sheet, the event still works.

The below code will add and show the name of the sheet that is newly added.

The are many more events of the workbook object. We can’t discuss them all here. If you want to know about some specific event then ask in the comments section below. I hope I was able to explain the basics of the workbook events in this article. Let me know if it helped you in the comments section below.
Related Articles:

Using Worksheet Change Event To Run Macro When any Change is Made | So to run your macro whenever the sheet updates, we use the Worksheet Events of VBA.

Run Macro If Any Change Made on Sheet in Specified Range | To run your macro code when the value in a specified range changes, use this VBA code. It detects any change made in the specified range and will fire the event.

Simplest VBA Code to Highlight Current Row and Column Using | Use this small VBA snippet to highlight the current row and column of the sheet.

50 Excel Shortcuts to Increase Your Productivity | Get faster at your task. These 50 shortcuts will make your work even faster on Excel.

The VLOOKUP Function in Excel | This is one of the most used and popular functions of excel that is used to lookup value from different ranges and sheets.

COUNTIF in Excel 2016 | Count values with conditions using this amazing function. You don’t need to filter your data to count specific value. Countif function is essential to prepare your dashboard.

How to Use SUMIF Function in Excel | This is another dashboard essential function. This helps you sum up values on specific conditions.

Источник

Hopefully this question hasn’t already been asked, I tried searching for an answer and couldn’t find anything.

This is probably a simple question, but I am writing my first macro in excel and am having a problem that I can’t find out a solution to. I wrote a couple of macros that basically sum up columns dynamically (so that the number of rows can change and the formula moves down automatically) based on a value in another column of the same row, and I call those macros from the event Workbook_SheetChange.

The problem I’m having is, I change a cell’s value from my macro to display the result of the sum, and this then calls Workbook_SheetChange again, which I do not want. Right now it works, but I can trace it and see that Workbook_SheetChange is being called multiple times. This is preventing me from adding other cell changes to the macros, because then it results in an infinite loop.

I want the macros to run every time a change is made to the sheet, but I don’t see any way around allowing the macros to change a cell’s value, so I don’t know what to do. I will paste my code below, in case it is helpful.

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Dim Row As Long
    Dim Col As Long
    Row = Target.Row
    Col = Target.Column
    If Col <> 7 Then
        Range("G" & Row).Select
        Selection.Formula = "=IF(F" & Row & "=""Win"",E" & Row & ",IF(F" & Row & "=""Loss"",-D" & Row & ",0))"
        Target.Select
    End If
    Call SumRiskColumn
End Sub

Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Call SumOutcomeColumn
End Sub

Sub SumOutcomeColumn()
    Dim N As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Cells(N + 1, "G").Formula = "=SUM(G2:G" & N & ")"
End Sub

Sub SumRiskColumn()
    Dim N As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    Dim CurrTotalRisk As Long
    CurrTotalRisk = 0
    For i = 2 To N
        If IsEmpty(ActiveSheet.Cells(i, 6)) And Not IsEmpty(ActiveSheet.Cells(i, 1)) And Not IsEmpty(ActiveSheet.Cells(i, 2)) And Not IsEmpty(ActiveSheet.Cells(i, 3)) Then
            CurrTotalRisk = CurrTotalRisk + ActiveSheet.Cells(i, 4).Value
        End If
    Next i
    Cells(N + 1, "D").Value = CurrTotalRisk
End Sub

Thank you for any help you can give me! I really appreciate it.

Понравилась статья? Поделить с друзьями:
  • Workbook one word or two
  • Workbook object in excel vba
  • Workbook not found excel
  • Workbook names from excel
  • Workbook file name excel