On change sheet excel vba

Return to VBA Code Examples

Worksheet_Change Event

You may want to run a macro when a cell changes. A popular use of this ability is to have custom code validate a cell after a change is made. It’s easy to do this by using the worksheet objects change event.

In the Visual Basic Editor you must first double click the sheet name where the cell changes that activates the macro. This opens the code window for that sheet object. In this case I wanted to run a macro when a cell in Sheet1 changes.

worksheet change event

After opening the code window for the Worksheet you place your code in the Worksheet_Change event. The following example will display a message box if the contents of cell A1 change. First the subroutine fires if any cell changes, then the use of an IF..Then statement will run the code only if cell A1 was the cell that changed based on the If…Then.


Private Sub Worksheet_Change(ByVal Target As Range)



If Target.Address = "$A$1" Then

     MsgBox "This Code Runs When Cell A1 Changes!"

End If



End Sub

You can place your code directly in the Worksheet_Change subroutine or call another macro from there.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro – A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

alt text

Learn More!

This Excel VBA tutorial explains how to use Worksheet.Change Event.

You may also want to read:

Excel VBA get value before Worksheet_Change event

Excel automatically refresh pivot table

VBA Excel Worksheet_Change Event

Excel predefines some popular actions that  you would do on different Objects (worksheet, workbook, button, etc), those actions are called Event. For example, activating a worksheet is an Event, closing a workbook is an Event, clicking on a button is an event. Each Object has its own list of Events, Workbook has a list of Events (e.g. close workbook, open workbook), worksheet has a list of Events (e.g. activate worksheet, edit a Cell).

If you perform an Event, say, closing a workbook, your desired code can be triggered. For example, you may want to save a workbook automatically when you close a workbook, or you may want a welcome message box to pop up when a workbook is opened. Event is a Sub Procedure (begin with Private Sub and end with End Sub) and is generated automatically (see in the below section) with a specific name, you can call a Sub Procedure or write your own code within the Event code.

Excel Worksheet_Change Event is an Event triggered when a you leave a Cell from edit mode (even no value is changed). For example, you double click on Cell A1 to enter edit mode, the event is triggered as you press “Enter” or click on any other Cell to exit the edit mode. Excel Worksheet_Change Event is not about value change of a Cell (of course the Event will trigger if you change a value), don’t be misled by the name.

If you want to know how to capture the initial value before change in order to compare the old and new value, read the below article

Excel VBA get value before Worksheet_Change event

How to insert Excel Worksheet_Change Event

Like all other worksheet events, you have to define the event and your desired actions within a specific worksheet where you want to Macro to trigger, each worksheet can have its own independent events.

1) Press Alt+F11 to enter into Visual Basic Editor

2) In the Project Explorer Window on the left, double click on the target worksheet

3) On top of the coding area, select “Worksheet” in the drop down box on the left, and then select “Change”.

4) Now you should be able to see two lines of code as below. Insert your action code between the two lines.

worksheet_change_event_01

Example of Excel Worksheet_Change Event

For example, I want to prompt a message box if column A value >100.

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Column = 1 And Target.Value > 100 Then
        MsgBox ("Column A value >100")
    End If
End Sub

In the above code, “Target” is the Range you make a change. Target.Column = 1 bounds the checking to column A.

Trigger Macro when Value Changes

Below is a solution I copied and pasted from Microsoft Community that was answered by me.

Question

How can you instruct a macro to run when a certain cell changes?

For example, as soon as text in cell A1 changes, a macro is triggered.

Answer

Private Sub Worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target, Range("A1:B10")) Is Nothing Then
     Dim OldValue As Variant
     Application.EnableEvents = False
     Application.Undo
     OldValue = Target.Value
     Application.Undo
     Application.EnableEvents = True
     If OldValue <> Target.Value Then
        'Your Macro
     End If
  End If
 End Sub

OR

Dim oldValue As Variant
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:B10")) Is Nothing Then
        oldValue = Target.Value
    End If
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
    If Not Intersect(Target, Range("A1:B10")) Is Nothing Then
        If Target.Value <> oldValue Then
            'Do something
        End If
    End If
End Sub

Outbound links

http://msdn.microsoft.com/en-us/library/office/ff839775%28v=office.15%29.aspx#AboutContributor

Automatically Run Excel Macros When a Cell Changes

VBA Change to a Single Cell

In Excel a Worksheet Change Event is a trigger for a macro when a cell or group of cells change.  I will start out by showing how a change to a single cell can trigger an action.  The following will colour cell B2 Red whenever the cell changes.  The following uses the(ByVal Target As Range) line which uses the Variable named Target.  The Target is the Range which will trigger an action.  You assign the Range within the code itself.

The following YouTube video takes you the cell change event, both a single cell and multiple cells. The following Excel file goes with the video.

Change Cell.xlsm

Before you fill your boots with the following it is worth mentioning that when you employ the use of the VBA change events you lose the ability to undo in Excel.  Normally Excel keeps a record of a number of actions.

The VBA code to perform this action needs to go in the sheet object you want to perform the event.  If you wanted to put the code in Sheet1 then you would double click on the sheet you wish to run the code from.

Excel VBA Change Event

The following is an example of Excel VBA coding you could put in Sheet1 or any of the other sheet objects.

In the example above you need to keep the $ (absolute sign) or the code will not work.  So when referencing a single cell the range reference needs to be absolute.

«$B$2”

The following VBA performs the same action as the above example.  It is a little more flexible if you wish to add to the range.  Once Inside the Worksheet Change Event, if the Target falls within the defined Range and the cell contents change, it will trigger an action inside VBA.

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range) ‘Excel VBA with more cells in the range.

If Not Intersect(Target, Range(«B2»)) Is Nothing Then

Target.EntireRow.Interior.ColorIndex=15

End If

End Sub

Disable Events

Occasionally one of the things you may wish to do with the cell that is changing is delete, copy, cut or some other action which triggers a circular loop.  For example, if you wanted to move a line to another sheet which met a condition, when the condition was met you would trigger the Change Event and when you deleted the row you would start another change event.  This second change event would cause a debug error.  To get around this you can turn Events off at the start of the procedure and turn them back on at the end of the procedure.

The line of code is;

Application.EnableEvents=False

and the following is an example of how it might be used.

Private Sub Worksheet_Change(ByVal Target As Range) ‘Excel VBA change event test for close.

If Not Intersect(Target, Range(«A2», Range(«A» & Rows.Count).End(xlUp))) Is Nothing Then

Application.EnableEvents=False
If Target=»Closed» Then

Target.EntireRow.Copy Sheet2.Range(«A1»).End(xlDown)(2)
Target.EntireRow.Delete

End If

End If
Application.EnableEvents=True

End Sub

The VBA  macro will copy the entire row from one sheet to another and delete the row which was just copied.  The example is shown in the file below.

VBA Worksheet Change Event Multiple Cells

When we want to perform an action when more than one cell is changed we can use the following VBA code to change a larger range. It focuses on shifting the range within the Target. The following is an example of a change event where if the cells from A2:A10 change the procedure will trigger an action.

Option Explicit ‘Excel worksheet change event Range A1 to A10
Private Sub Worksheet_Change(ByVal Target As Range)

If Not Intersect(Target, Range(«A2:A10»)) Is Nothing Then

Target.EntireRow.Interior.ColorIndex=15

End If

End Sub

VBA Double Click Event

A double click event in Excel VBA is self explanatory.  It will occur on double click of a cell in the Target range.  So if you have a range between C13 and O26 where you want to perform an action on Double click, the following should help.

‘Excel worksheet double click change event Range C13 to O26
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

If Not Intersect(Target, Range(«C13:O26»)) Is Nothing Then

Target.Value=ActiveCell.Offset(19, 0).Value

End If

End Sub

VBA Before Save Event

This event is triggered as the name suggests before each Save. So as the save Excel file icon is clicked the code which is associated with this event will trigger.

The before Save event needs to go into the ThisWorkbook Object in order for it to run.

Excel change events

The following Excel VBA macro will put the word False in Cell A1 before the file is saved.

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

Sheet1.Cells(1, 1)=False

End Sub

Worksheet Change Event in VBA and Preventing Event Loops

Related Links: 

Excel VBA Events, Event Handlers, Trigger a VBA Macro.

Worksheet Selection Change Event, Excel VBA.

————————————————————————   

Contents:

Worksheet_Change Event

Preventing Event Loops with Application.EnableEvents = False

————————————————————————   

Worksheet_Change Event:

You can auto run a VBA code, when content of a worksheet cell changes, with the Worksheet_Change event. The change event occurs when cells on the worksheet are changed either by the user, or by any VBA application or by an external link, but not when a cell changes due to recalculation as a result from formula or due to format change. For changes made by calculation, use Worksheet_Calculate event.

Worksheet change procedure is installed with the worksheet, ie. it must be placed in the code module of the appropriate Sheet object. To create a worksheet change event: use the Visual Basic Editor -> in the Project Explorer, double click on the appropriate sheet (under ‘Microsoft Excel Objects’ which is under the VBAProject/name of your workbook) -> in the Code window, select «Worksheet» from the left-side «General» drop-down menu and then select «Change» from the right-side «Declarations» drop-down menu. You will get a procedure «shell» in the code window as follows:

Private Sub Worksheet_Change(ByVal Target As Range)

End Sub

Target is a parameter of data type Range (ie. Target is a Range Object). It refers to the changed Range and can consist of one or multiple cells. If Target is in the defined Range, and its value or content changes, it will trigger the vba procedure. If Target is not in the defined Range, nothing will happen in the worksheet. In this manner, you can limit the events to a particular range for both the Change and SelectionChange events. This can be done in multiple ways:

Using Target Address. Trigger the procedure, if a single cell (A5) value is changed:

If Target.Address = «$A$5» Then MsgBox «Success»

If Target.Address = Range(«$A$5»).Address Then MsgBox «Success»

If Target.Address = Range(«A5»).Address Then MsgBox «Success»

Using Target Address. If cell (A1) or cell (A3) value is changed:

If Target.Address = «$A$1» Or Target.Address = «$A$3» Then MsgBox «Success»

Using Target Address. If any cell(s) value other than that of cell (A1) is changed:

If Target.Address <> «$A$1» Then MsgBox «Success»

The following use of Target.Address is not correct, and the code will not run:

If Target.Address = «$a$5» Then MsgBox «Success»

If Target.Address = «A1» Then MsgBox «Success»

If Target.Address = «$A$1:$A$10» Then MsgBox «Success»

If Target.Address = Range(«$A$1:$A$10») Then MsgBox «Success»

Note: Target.Address should be an absolute reference [unless used as Range(«A5»).Address — see above] and in Caps. Use this to run code when content of a single cell is changed or when any cell(s) other than a specific cell is changed.

Trigger the procedure, if any cell in a column(s) is changed, say for any change in a cell in column B or column C:

If Target.Column = 2 Or Target.Column = 3 Then MsgBox «Success»

Intersect method for a single cell. If Target intersects with the defined Range of A1 ie. if cell (A1) value is changed, the code is triggerred:

If Not Application.Intersect(Target, Range(«A1»)) Is Nothing Then MsgBox «Success»

Trigger the procedure, if at least one cell of Target is A1,B2,C3:

If Not Application.Intersect(Target, Range(«A1,B2,C3»)) Is Nothing Then MsgBox «Success»

At least one cell of Target is within the range C5:D25:

If Not Application.Intersect(Target, Me.Range(«C5:D25»)) Is Nothing Then MsgBox «Success»

If you want the code to run when only a single cell in Range(«C1:C10») is changed and do nothing if multiple cells are changed:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range(«C1:C10»)) Is Nothing Or Target.Cells.Count > 1 Then

Exit Sub

Else

MsgBox «Success»

End If

End Sub

Preventing Event Loops with Application.EnableEvents = False

Example of a recursive loop code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Application.Intersect(Target, Range(«A1:A10»)) Is Nothing Then

Range(«A5»).Value = Range(«A5»).Value + 1

End If

End Sub

Recursive Event Loop:

If, at each runtime, the worksheet_change event changes the content of a cell which itself is part of the Target Range (ie. which triggers the change event), it will result in reprocessing the change event repeatedly.  Recursion is the process of repeating in a similar way viz. when the procedure calls itself. Refer to above example of a recursive loop code, if any cell content in Range(«A1:A10») is changed by the user, the cell A5 value will change and increment by 1; this will again trigger the change event [because of change in value of cell A5 which is in the Target Range(«A1:A10»)] and will in turn change the cell A5 value by incrementing it by 1; and then this change in cell A5 will again trigger the change event and change the cell A5 value by incrementing it by 1; and so on. This will result in a recursive loop which might result in a ‘Out Of Stack Space’ untrappable error, or depending on the Excel setting, the loop might terminate at a threshold limit of say 100. To prevent this, enter the following at the beginning of the code: Application.EnableEvents = False. This means that any change made by the VBA code will not trigger any event and will not enable restarting the worksheet_change event. EnableEvents is not automatically changed back to True, this should be specifically done in your code, by adding the following line at the end of the code: Application.EnableEvents = True. Meanwhile, if during runtime, your code encounters an error, you will need an ErrorHandler (to change EnableEvents back to True) because events have been disabled in the beginning of the code. This can be done as follows. 

ErrorHandler, Example 1:

Private Sub Worksheet_Change(ByVal Target As Range)

‘on the occurrence of an error procedure flow is directed to the error-handling routine (ie. ErrHandler) which handles the error
On Error GoTo ErrorHandler
 

‘to prevent recursion — so that any change made by code will not trigger an event to restart the Worksheet_Change event 

Application.EnableEvents = False

‘on changing cell A1 or B1, go to ErrorHandler which reverts EnableEvents to True & then exit sub

If Target.Address = «$A$1» Or Target.Address = «$B$1» Then GoTo ErrorHandler

‘if value of any cell in column 1 or 2 is changed

If Target.Column = 1 Or Target.Column = 2 Then

‘if changed cell value is numeric ie. new value is not text

If IsNumeric(Target) Then

‘increment cell B2 value by 1

Range(«B2»).Value = Range(«B2»).Value + 1

End If

End If

‘EnableEvents is not automatically changed back to True & hence this needs to be done specifically at the end of the code before exit.

‘because an exit statement (ex. Exit Sub) is not placed above, the error-handling routine will also execute when there is no error.

ErrorHandler:

Application.EnableEvents = True

End Sub

ErrorHandler, Example 2:

Private Sub Worksheet_Change(ByVal Target As Range)

On Error Resume Next  ‘skip all run-time errors

If Target.Address = «$A$1» Or Target.Address = «$B$1» Then Exit Sub

Application.EnableEvents = False

 
If Target.Column = 1 Or Target.Column = 2 Then

If IsNumeric(Target) Then

Range(«B2»).Value = Range(«B2»).Value + 1

End If

End If

Application.EnableEvents = True

On Error GoTo 0  ‘Turn off error trapping and re-allow run time errors

End Sub

On Error Statements explained:

On Error Resume Next: Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point.

The On Error GoTo 0 statement turns off error trapping.  It disables enabled error handler in the current procedure and resets it to Nothing.

On Error GoTo Line: Enables the error-handling routine that starts at the specified Line. The On Error GoTo statement traps all errors, regardless of the exception class.

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

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

What is a Worksheets Event Handler?

A worksheet event handler is a subroutine that is local to a worksheet module.

Where to write Worksheet Event Handler Code?

The worksheet Events are written in sheets objects only. If you write a worksheet event in some module or class module, there will be no error but they will just won’t work.

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

How to write code for a specific event on the worksheet?

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 worksheet. Now 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. You can’t use them for other subroutines on a sheet. In a module, they will work as a normal subroutine.

Important: Each subroutine from that list will run on the specified event.
One type of worksheet event procedure can be written only once on one sheet. If you write two same event handling procedures on one sheet, 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 Worksheet_Change (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 the entire sheet then the code will be:

Private Sub Worksheet_Change(ByVal Target As Range)
  'do somehting 
  Msgbox "done something"
End Sub

The «Target» is the Active cell always.

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

Private Sub Worksheet_Change(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.

If you want to target a range then use the below example:

Run Macro If Any Change Made on Sheet in Specified Range

2. The Worksheet_SelectionChange(ByVal Target As Range) Event

As the name suggests, this event triggers when the selection changes. In other words, if your cursor is in Cell A1 and it moves to some other cell, the code in this subroutine will run.

The below code will change the active cells color if whenever it changes and if it is an even row.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 If Target.Row Mod 2 = 0 Then
    Target.Interior.ColorIndex = 22
 End If
End Sub

Now, whenever my cursor will move on even row, it will be colored. Odd row cells will be spared.

Another Example of the Worksheet_SelectionChange event:

Simplest VBA Code to Highlight Current Row and Column Using

3. The Worksheet_Activate() Event

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

Private Sub Worksheet_Activate()

End Sub

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

Private Sub Worksheet_Activate()

  MsgBox "You are on " & ActiveSheet.Name

End Sub

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

4. The Worksheet_Deactivate() Event

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

Private Sub Worksheet_Deactivate()
'your code
'
End Sub

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

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


5. The Worksheet_BeforeDelete() Event

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

Private Sub Worksheet_BeforeDelete()

End Sub

The below code will ask you if you want to copy the content of the about-to-delete sheet.

Private Sub Worksheet_BeforeDelete()
    ans = MsgBox("Do you want to copy the content of this sheet to a new sheet?", vbYesNo)
    If ans = True Then
    'code to copy
 End If
End Sub

6. The Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Event

This event triggers when you double click on the targeted cell. The syntax of this VBA Worksheet Event is:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

End Sub

If you don’t set the target cell or range, it will fire on every double click on the sheet.
The Cancel variable is a boolean variable. If you set it True, the default action won’t happen. It means if you double click on the cell it won’t get into editing mode.
The below code will make the cell fill with a color if you double click on any cell.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)

Cancel = True
Target.Interior.ColorIndex = 7

End Sub

The below code targets the cell A1. If it is already filled with the specified color then it will vanish the color. It is much like a like button or check box.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
   If Target.Address = "$A$1" Then
   
   Cancel = True
    If Target.Interior.ColorIndex = 4 Then
        Target.Interior.ColorIndex = xlColorIndexNone
    Else
        Target.Interior.ColorIndex = 4
    End If
    
   End If
   
End Sub

7. The Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean) Event

This event triggers when you Right-Click on the targeted cell. The syntax of this VBA Worksheet Event is:

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
   Cancel = True
   '
   'your code
   '
End Sub

The below code will fill the cell with value 1 if you right-click on it. It won’t show the default right-click options since we have set the «Cancel» Operator to True.

Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
   Cancel = True
   Target.Value = 1
End Sub

8. The Worksheet_Calculate() Event

If you want something to happen when a excel calculates a sheet, use this event. It will trigger whenever excel calculates a sheet. The syntax is simple:

Private Sub Worksheet_Calculate()
  '
   'your code
   '  
End Sub

6. The Worksheet_FollowHyperlink(ByVal Target As Hyperlink) Event

This procedure will run when you click on a hyperlink on the sheet.  The basic syntax of this event handler is:

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
    '
   'your code
   ' 

End Sub

You can set the target hyperlink if you want. If you don’t set the target hyperlink, it will get executed if you click on any hyperlink on the code containing sheet.

So yeah guys, these were some basic worksheet events that will be handy if you know about them. Below are some related articles that you may like to read.

If you have any doubts regarding this article or any other excel/VBA related article, let us know 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.2. События рабочего листа (Worksheet Events)
  2. Worksheet_SelectionChange (Открытие книги)
  3. Worksheet_Activate (Событие активации листа)
  4. Worksheet_Deactivate (Событие деактивации листа)
  5. Worksheet_BeforeDoubleClick (Событие двойного щелчка по ячейке)
  6. Worksheet_BeforeRightClick (Событие перед правым кликом)
  7. Worksheet_Calculate (Событие перерасчета листа)
  8. Worksheet_Change (Событие изменения содержимого ячейки)
  9. Worksheet_FollowHyperlink (Событие нажатия на ссылку)
  10. Temporarily deactivate all events (Временное отключение всех событий)
  11. Событие Worksheet.Change (Excel)
  12. Синтаксис
  13. Параметры
  14. Возвращаемое значение
  15. Замечания
  16. Пример
  17. Поддержка и обратная связь
  18. Worksheet Change and SelectionChange Events
  19. Worksheet_Change event procedure
  20. Monitor changes made to specific cell or range
  21. Worksheet_Change Vs. Worksheet_Calculate
  22. Worksheet_SelectionChange event procedure
  23. Take some action when specific cells or ranges selected
  24. VBA Excel Worksheet.Change Event
  25. VBA Excel Worksheet_Change Event
  26. How to insert Excel Worksheet_Change Event
  27. Example of Excel Worksheet_Change Event
  28. Trigger Macro when Value Changes
  29. Question
  30. Excel VBA
  31. Worksheet Change Event, Excel VBA

VBA-Урок 11.2. События рабочего листа (Worksheet Events)

На предыдущем уроке мы рассматривали события, относящиеся к целой книги. Сейчас мы сфокусируемся на событиях связанных с отдельным листом.

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

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

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

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

Worksheet_Activate (Событие активации листа)

Это событие возникает при активации рабочего листа

Worksheet_Deactivate (Событие деактивации листа)

Это событие возникает при активации другого рабочего листа

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

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

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

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

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

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

Worksheet_Change (Событие изменения содержимого ячейки)

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

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

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

Temporarily deactivate all events (Временное отключение всех событий)

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

Источник

Событие Worksheet.Change (Excel)

Происходит при изменении ячеек на листе пользователем или внешней ссылкой.

Синтаксис

expression. Изменение (целевой объект)

Выражение Переменная, представляющая объект Worksheet .

Параметры

Имя Обязательный или необязательный Тип данных Описание
Target (Целевое значение) Обязательный Диапазон Измененный диапазон. Может быть несколько ячеек.

Возвращаемое значение

Nothing

Замечания

Это событие не возникает при изменении ячеек во время пересчета. Используйте событие Calculate для перехвата пересчета листа.

Пример

В следующем примере кода цвет измененных ячеек изменяется на синий.

В следующем примере кода проверяется, что при изменении значения ячейки измененная ячейка находится в столбце A, а также если измененное значение ячейки больше 100. Если значение больше 100, смежная ячейка в столбце B изменяется на красный цвет.

В следующем примере кода значения в диапазоне A1:A10 задаются в верхнем регистре при вводе данных в ячейку.

Поддержка и обратная связь

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.

Источник

Worksheet Change and SelectionChange Events

In this tutorial, we’ll discuss the Change and ChangeSelection worksheet events. The Worksheet_Change event-handler procedure executes whenever any cell in the worksheet is changed and Worksheet_SelectionChange event-handler procedure executes when the selection on the worksheet is changed.

The worksheet event-handler procedures must be in the code module for that worksheet. Put them somewhere else, and they won’t work. You can quickly access that code window by right-clicking the worksheet’s tab and selecting the View Code :

Worksheet_Change event procedure

The Change event triggers whenever any cell in the worksheet is changed. Excel uses the Worksheet_Change event-handler procedure to trap the Change event. The Worksheet_Change procedure accepts Target (the Range object) as the parameter which represents the cell that was changed. The following example displays a message box that shows the address of the Target range:

Try making some changing in cells, every time you make changes, a message box displays the address of the cell that changed.

Monitor changes made to specific cell or range

The Worksheet_Chnage procedure receives the Target as Range object which represents the changed cell(s). In this example, we compare the Target with the given cell range A1:A10 using Intersect method:

A popup message box appears when a change made in the given cell range:

Worksheet_Change Vs. Worksheet_Calculate

The Worksheet_Change event procedure is not executed by a calculation change, for example, when a formula returning a different value. You must use the Worksheet_Calculate event procedure to capture the changes to values in cells that contain formulas.

Worksheet_SelectionChange event procedure

The Worksheet_SelectionChange event procedure executes when a cell is selected. The following code highlights the active cell with a red color every time a different cell is selected:

The first statement removes the background color for all cells in the worksheet. Next, the the active cell is shaded with red color.

Take some action when specific cells or ranges selected

In many cases, you need to execute a piece of code when certain cells or ranges selected. To accomplish this, we use the Intersect method on the Target (selected cell or range) and the range containing the specific cell to verify the Target is one of the specific cells or ranges. If the Target is in the range containing the specific cells, you can execute the code.

The following code highlights the active cell with a red color every time a different cell is selected:

Источник

VBA Excel Worksheet.Change Event

This Excel VBA tutorial explains how to use Worksheet.Change Event.

You may also want to read:

VBA Excel Worksheet_Change Event

Excel predefines some popular actions that you would do on different Objects (worksheet, workbook, button, etc), those actions are called Event. For example, activating a worksheet is an Event, closing a workbook is an Event, clicking on a button is an event. Each Object has its own list of Events, Workbook has a list of Events (e.g. close workbook, open workbook), worksheet has a list of Events (e.g. activate worksheet, edit a Cell).

If you perform an Event, say, closing a workbook, your desired code can be triggered. For example, you may want to save a workbook automatically when you close a workbook, or you may want a welcome message box to pop up when a workbook is opened. Event is a Sub Procedure (begin with Private Sub and end with End Sub) and is generated automatically (see in the below section) with a specific name, you can call a Sub Procedure or write your own code within the Event code.

Excel Worksheet_Change Event is an Event triggered when a you leave a Cell from edit mode (even no value is changed). For example, you double click on Cell A1 to enter edit mode, the event is triggered as you press “Enter” or click on any other Cell to exit the edit mode. Excel Worksheet_Change Event is not about value change of a Cell (of course the Event will trigger if you change a value), don’t be misled by the name.

If you want to know how to capture the initial value before change in order to compare the old and new value, read the below article

How to insert Excel Worksheet_Change Event

Like all other worksheet events, you have to define the event and your desired actions within a specific worksheet where you want to Macro to trigger, each worksheet can have its own independent events.

1) Press Alt+F11 to enter into Visual Basic Editor

2) In the Project Explorer Window on the left, double click on the target worksheet

3) On top of the coding area, select “Worksheet” in the drop down box on the left, and then select “Change”.

4) Now you should be able to see two lines of code as below. Insert your action code between the two lines.

Example of Excel Worksheet_Change Event

For example, I want to prompt a message box if column A value >100.

In the above code, “Target” is the Range you make a change. Target.Column = 1 bounds the checking to column A.

Trigger Macro when Value Changes

Below is a solution I copied and pasted from Microsoft Community that was answered by me.

Question

How can you instruct a macro to run when a certain cell changes?

For example, as soon as text in cell A1 changes, a macro is triggered.

Источник

Excel VBA

Worksheet Change Event, Excel VBA

User Rating: 5 / 5

Worksheet Change Event in VBA and Preventing Event Loops

Related Links:

Contents:

Worksheet_Change Event:

You can auto run a VBA code, when content of a worksheet cell changes, with the Worksheet_Change event. The change event occurs when cells on the worksheet are changed either by the user, or by any VBA application or by an external link, but not when a cell changes due to recalculation as a result from formula or due to format change. For changes made by calculation, use Worksheet_Calculate event.

Worksheet change procedure is installed with the worksheet, ie. it must be placed in the code module of the appropriate Sheet object. To create a worksheet change event: use the Visual Basic Editor -> in the Project Explorer, double click on the appropriate sheet (under ‘Microsoft Excel Objects’ which is under the VBAProject/name of your workbook) -> in the Code window, select «Worksheet» from the left-side «General» drop-down menu and then select «Change» from the right-side «Declarations» drop-down menu. You will get a procedure «shell» in the code window as follows:

Private Sub Worksheet_Change(ByVal Target As Range)

Target is a parameter of data type Range (ie. Target is a Range Object). It refers to the changed Range and can consist of one or multiple cells. If Target is in the defined Range, and its value or content changes, it will trigger the vba procedure. If Target is not in the defined Range, nothing will happen in the worksheet. In this manner, you can limit the events to a particular range for both the Change and SelectionChange events. This can be done in multiple ways:

Using Target Address. Trigger the procedure, if a single cell (A5) value is changed:

If Target.Address = «$A$5» Then MsgBox «Success»

If Target.Address = Range(«$A$5»).Address Then MsgBox «Success»

If Target.Address = Range(«A5»).Address Then MsgBox «Success»

Using Target Address. If cell (A1) or cell (A3) value is changed:

If Target.Address = «$A$1» Or Target.Address = «$A$3» Then MsgBox «Success»

Using Target Address. If any cell(s) value other than that of cell (A1) is changed:

If Target.Address <> «$A$1» Then MsgBox «Success»

The following use of Target.Address is not correct, and the code will not run:

If Target.Address = «$a$5» Then MsgBox «Success»

If Target.Address = «A1» Then MsgBox «Success»

If Target.Address = «$A$1:$A$10» Then MsgBox «Success»

If Target.Address = Range(«$A$1:$A$10») Then MsgBox «Success»

Note : Target.Address should be an absolute reference [unless used as Range(«A5»).Address — see above] and in Caps. Use this to run code when content of a single cell is changed or when any cell(s) other than a specific cell is changed.

Trigger the procedure, if any cell in a column(s) is changed, say for any change in a cell in column B or column C:

If Target.Column = 2 Or Target.Column = 3 Then MsgBox «Success»

Intersect method for a single cell. If Target intersects with the defined Range of A1 ie. if cell (A1) value is changed, the code is triggerred:

If Not Application.Intersect(Target, Range(«A1»)) Is Nothing Then MsgBox «Success»

Trigger the procedure, if at least one cell of Target is A1,B2,C3:

If Not Application.Intersect(Target, Range(«A1,B2,C3»)) Is Nothing Then MsgBox «Success»

At least one cell of Target is within the range C5:D25:

If Not Application.Intersect(Target, Me.Range(«C5:D25»)) Is Nothing Then MsgBox «Success»

If you want the code to run when only a single cell in Range(«C1:C10») is changed and do nothing if multiple cells are changed:

Private Sub Worksheet_Change(ByVal Target As Range)

If Intersect(Target, Range(«C1:C10»)) Is Nothing Or Target.Cells.Count > 1 Then

End Sub

Preventing Event Loops with Application.EnableEvents = False

Example of a recursive loop code:

Private Sub Worksheet_Change(ByVal Target As Range)

If Not Application.Intersect(Target, Range(«A1:A10»)) Is Nothing Then

Range(«A5»).Value = Range(«A5»).Value + 1

End Sub

Recursive Event Loop:

If, at each runtime, the worksheet_change event changes the content of a cell which itself is part of the Target Range (ie. which triggers the change event), it will result in reprocessing the change event repeatedly. Recursion is the process of repeating in a similar way viz. when the procedure calls itself. Refer to above example of a recursive loop code, if any cell content in Range(«A1:A10») is changed by the user, the cell A5 value will change and increment by 1; this will again trigger the change event [because of change in value of cell A5 which is in the Target Range(«A1:A10»)] and will in turn change the cell A5 value by incrementing it by 1; and then this change in cell A5 will again trigger the change event and change the cell A5 value by incrementing it by 1; and so on. This will result in a recursive loop which might result in a ‘Out Of Stack Space’ untrappable error, or depending on the Excel setting, the loop might terminate at a threshold limit of say 100. To prevent this, enter the following at the beginning of the code: Application.EnableEvents = False. This means that any change made by the VBA code will not trigger any event and will not enable restarting the worksheet_change event. EnableEvents is not automatically changed back to True, this should be specifically done in your code, by adding the following line at the end of the code: Application.EnableEvents = True. Meanwhile, if during runtime, your code encounters an error, you will need an ErrorHandler (to change EnableEvents back to True) because events have been disabled in the beginning of the code. This can be done as follows.

ErrorHandler, Example 1:

Private Sub Worksheet_Change(ByVal Target As Range)

‘on the occurrence of an error procedure flow is directed to the error-handling routine (ie. ErrHandler) which handles the error
On Error GoTo ErrorHandler

‘to prevent recursion — so that any change made by code will not trigger an event to restart the Worksheet_Change event

‘on changing cell A1 or B1, go to ErrorHandler which reverts EnableEvents to True & then exit sub

If Target.Address = «$A$1» Or Target.Address = «$B$1» Then GoTo ErrorHandler

‘if value of any cell in column 1 or 2 is changed

If Target.Column = 1 Or Target.Column = 2 Then

‘if changed cell value is numeric ie. new value is not text

If IsNumeric(Target) Then

‘increment cell B2 value by 1

Range(«B2»).Value = Range(«B2»).Value + 1

‘EnableEvents is not automatically changed back to True & hence this needs to be done specifically at the end of the code before exit.

‘because an exit statement (ex. Exit Sub) is not placed above, the error-handling routine will also execute when there is no error.

End Sub

ErrorHandler, Example 2:

Private Sub Worksheet_Change(ByVal Target As Range)

On Error Resume Next ‘skip all run-time errors

If Target.Address = «$A$1» Or Target.Address = «$B$1» Then Exit Sub

If Target.Column = 1 Or Target.Column = 2 Then

If IsNumeric(Target) Then

Range(«B2»).Value = Range(«B2»).Value + 1

On Error GoTo 0 ‘Turn off error trapping and re-allow run time errors

End Sub

On Error Statements explained:

On Error Resume Next: Specifies that when a run-time error occurs, control goes to the statement immediately following the statement where the error occurred, and execution continues from that point.

The On Error GoTo 0 statement turns off error trapping. It disables enabled error handler in the current procedure and resets it to Nothing.

On Error GoTo Line: Enables the error-handling routine that starts at the specified Line. The On Error GoTo statement traps all errors, regardless of the exception class.

Источник

In this tutorial, we’ll discuss the Change and ChangeSelection worksheet events. The Worksheet_Change event-handler procedure executes whenever any cell in the worksheet is changed and Worksheet_SelectionChange event-handler procedure executes when the selection on the worksheet is changed.

The worksheet event-handler procedures must be in the code module for that worksheet. Put them somewhere else, and they won’t work. You can quickly access that code window by right-clicking the worksheet’s tab and selecting the View Code:

Worksheet view code window

Worksheet_Change event procedure

The Change event triggers whenever any cell in the worksheet is changed. Excel uses the Worksheet_Change event-handler procedure to trap the Change event. The Worksheet_Change procedure accepts Target (the Range object) as the parameter which represents the cell that was changed. The following example displays a message box that shows the address of the Target range:

Private Sub Worksheet_Change(ByVal Target As Range)
 MsgBox Target.Address
End Sub

Try making some changing in cells, every time you make changes, a message box displays the address of the cell that changed.

Monitor changes made to specific cell or range

The Worksheet_Chnage procedure receives the Target as Range object which represents the changed cell(s). In this example, we compare the Target with the given cell range A1:A10 using Intersect method:

Private Sub Worksheet_Change(ByVal Target As Range)
 Dim MyRange As Range
 Set MyRange = Range("A1:A10")
 If Not Intersect(Target, MyRange) Is Nothing Then
  MsgBox ("You've changed the " & Target.Address)
 End If
End Sub

A popup message box appears when a change made in the given cell range:

Worksheet_Change Vs. Worksheet_Calculate

The Worksheet_Change event procedure is not executed by a calculation change, for example, when a formula returning a different value. You must use the Worksheet_Calculate event procedure to capture the changes to values in cells that contain formulas.

Worksheet_SelectionChange event procedure

The Worksheet_SelectionChange event procedure executes when a cell is selected. The following code highlights the active cell with a red color every time a different cell is selected:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 Cells.Interior.ColorIndex = 0
 Target.Interior.ColorIndex = 3
End Sub

The first statement removes the background color for all cells in the worksheet. Next, the the active cell is shaded with red color.

Take some action when specific cells or ranges selected

In many cases, you need to execute a piece of code when certain cells or ranges selected. To accomplish this, we use the Intersect method on the Target (selected cell or range) and the range containing the specific cell to verify the Target is one of the specific cells or ranges. If the Target is in the range containing the specific cells, you can execute the code.

The following code highlights the active cell with a red color every time a different cell is selected:

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
 Cells.Interior.ColorIndex = 0
 Dim MyRange As Range
 Set MyRange = Range("A1:A10")
 If Not Intersect(Target, MyRange) Is Nothing Then
  Target.Interior.ColorIndex = 3
 End If
End Sub

by updated Apr 05, 2020

Понравилась статья? Поделить с друзьями:
  • Omnisport excel толщина 8 3 мм
  • Omitting the word that
  • Omission of the word that
  • Olympics meaning of the word
  • Olympic sports word search