Excel vba on change event cell


August 15, 2015/



Chris Newman

How To Trigger Your VBA Macros To Run Based On A Specific Cell Value Change

Today we are going to discuss how you can automatically make your VBA code execute based on a specific cell value being changed. Behind the scenes, Excel keeps track of specific events that occur while the user is working on their spreadsheet. These tracked events are called Event Handlers and we can use Event Handlers as triggers to kick off our macros based on what our users are doing to their spreadsheets.

What Are Some Examples of Event Handlers?

There are a bunch of Event Handlers available to you and they fall into two categories: Workbook and Worksheet Events. What the handlers capture is fairly evident by their names, so I won’t go into detail on what each on does. But I will go ahead and list some of them out so you can have an idea of what is available to you.

Workbook Events

  • Open

  • SheetChange

  • SheetActivate

  • BeforeClose

  • BeforeSave

  • NewChart

Worksheet Events

  • Change

  • Activate

  • BeforeDelete

  • BeforeDoubleClick

  • BeforeRightClick

  • SelectionChange

Where Are Event Handlers Located?

Event Handlers are not stored in your typical module location. They are actually stored inside either your Workbook or Worksheet object. To get to the «coding area» of either your workbook or worksheet, you simply double-click ThisWorkbook or the sheet name (respectively) within your desired VBA Project hierarchy tree (within the Project Window of your Visual Basic Editor).

How Do I Add An Event Handler?

Event Handlers have very specific subroutine names and variables. It is very important not to have any typos within the sub name or the variables it declares. To guarantee avoidance of any typos, I always recommend having the Visual Basic Editor set up the Event Handler code for you. To do this,  select either Worksheet or Workbook from the Object drop-down box and then select the Event Handler you wish to use from the Procedure drop-down box.

VBA Event Handler Trigger Macro Code

Let’s Walk Through An Example!

Hopefully, you now have some sort of conceptual understanding of Event Handlers, but how do you use them in the real world? Let’s walk through a very simple example that will allow us to run some VBA code whenever the Cell G7 contains the word «yes» on our spreadsheet.

Below is going to be our interface where Excel will reveal a joke if you type the word «Yes» into the blank box (Cell G7).

Excel VBA Event Handler Trigger Macro Code

The Example in Action

You can see through the following diagram, immediately after I type in «Yes, tell me a joke!», a super-funny joke magically appears! 

Excel VBA Change Event Handler Trigger Macro Code

The VBA Behind The Spreadsheet

To get this spreadsheet working as intended, I needed to add an Event handler, to capture anytime there was a change to the cell G7. I choose to use the Change Event Handler to make this happen.

What the Change event captures is any change made to your spreadsheet (excluding formatting changes). You’ll notice that the Worksheet_Change subroutine has a variable named Target that gets fed into it. This variable is a Range-type and will be the cell that was last changed by the user. So if I changed the value in Cell A1, the Worksheet_Change subroutine would kick off and pass Cell A1 into the Target variable.

With this in mind, we are going to want to test the cell that was changed to see if it matches the cell we are concerned with. We can do this by starting our code off with a very simple IF Statement that acts as a door to the rest of the code. The IF statement checks to see if the cell(s) that was last changed intersects (or matches) cell G7.

‘Determine if change was made to cell G7
  If Not Intersect(Target, Range(«G7»)) Is Nothing Then

If the Target cell does not have access to get past the door, then the code ends and it will happen so fast, that your user won’t know anything has happened.

Below is the code in full that will test if the word «Yes» was entered into cell G7 anytime a change happens within Sheet1:

‘Remove Case Sensitivity
  Option Compare Text

Private Sub Worksheet_Change(ByVal Target As Range)

‘Determine if change was made to cell G7
  If Not Intersect(Target, Range(«G7»)) Is Nothing Then

        ‘Determine if the work «yes» is contained within cell G7
      If InStr(1, Range(«G7»), «Yes») > 0 Then
        Range(«G9»).Font.Color = Range(«F5»).Font.Color
      Else
        Range(«G9»).Font.Color = Range(«G9»).Interior.Color
      End If

    End If

End Sub

And here is a diagram of where you would place the code within your VBA Project:

Why Aren’t My Events Getting Captured?

Many people will turn off the tracking of Event to speed up their VBA code. If you are relying on capturing events within your spreadsheet and they don’t seem to be working, you can run the following command in the Immediate Window (use the shortcut Ctrl + g to make this window visible) within the Visual Basic Editor.

Just hit your enter key after typing the below phrase into the Immediate Window:

  Application.EnableEvents = True

Get The Example File Used In This Article

Sometimes seeing things in action may help you learn much better than reading about it in an article. That is why I am making the example I walked through in this article available to you. The workbook and its code are completely unlocked so you can dig in and discover how all the magic works.

If you would like to get a copy of the Excel file I used throughout this article, feel free to directly download the spreadsheet by clicking the download button below.

About The Author

Hey there! I’m Chris and I run TheSpreadsheetGuru website in my spare time. By day, I’m actually a finance professional who relies on Microsoft Excel quite heavily in the corporate world. I love taking the things I learn in the “real world” and sharing them with everyone here on this site so that you too can become a spreadsheet guru at your company.

Through my years in the corporate world, I’ve been able to pick up on opportunities to make working with Excel better and have built a variety of Excel add-ins, from inserting tickmark symbols to automating copy/pasting from Excel to PowerPoint. If you’d like to keep up to date with the latest Excel news and directly get emailed the most meaningful Excel tips I’ve learned over the years, you can sign up for my free newsletters. I hope I was able to provide you with some value today and I hope to see you back here soon!

— Chris
Founder, TheSpreadsheetGuru.com

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

14 Sep Run Code When Cell Values Change & Other Worksheet Events

Howdee! A common requirement when developing in Excel is the need to have code run while a user interacts with a report. That is to say, the user does not need to explicitly trigger your subroutine. Therefore, today I want to cover how to run code when cell values change, as well as a handful of other worksheet events that I’ve found useful over the years. There are more worksheet events that you can use to trigger code than I’ll cover here but I think these are the most important. For a full list, click here. With that said, let’s dive in!

I specifically mention this event because it’s the one you’ll likely find the most useful. It helps with everything from validating data entry to filtering data sets and even generating reports. To capture an event when a cell value changes, we actually subscribe to an event called “Worksheet_Change” via a private subroutine. Side note, when you have a piece of code tied to an event, it’s common to say that your subroutine is subscribing to that event. Think of it like a subscription to your favorite sports team’s news site, when something happens you expect the news service you subscribe to will alert you about it.

The easiest way to create these subscribers is to open your code editor using alt + F11 and selecting the worksheet object you want to edit by double-clicking on it in the project window on the top left. Once there, change the dropdown selection at the top that says “(General)” to “Worksheet” as pictured below. Next you can select any event you want from the dropdown on the top right, also pictured below (click on the images to view full size).

Once you select an event to subscribe to, the editor will automatically generate the necessary code snippet. It’s important that you don’t change the name of your subroutine as this is what is being triggered by the event. Most events also pass along information to their subscribers. For example, the Worksheet_Change event passes along the ByVal Target as Range variable. The ByVal keyword specifies that the underlying variable that Target represents cannot be altered by our stored procedure. So, if Target refers to cell A1, we can not use it to directly refer to cell A2 (we can however refer to it indirectly).

The Target variable refers to the cell we edit. So, if our cursor is in cell A1 and we press enter, the Target variable will refer to cell A1. This is important to remember if you’re going to be using any kind of offset to interact with the target variable.

Let’s say we want to validate that the value entered in column A was a number unless it was cell A1. This would allow the user to enter a header and a list of numbers. The code for that validation would look like this:

Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("A:A")) Is Nothing Then
    If Not Intersect(Target, Range("A1")) Is Nothing Then
        Exit Sub
    Else
        If Not IsNumeric(Target) Then
            MsgBox "Value must be numeric"
            Target.ClearContents
            Target.Activate
        End If
    End If
Else
    Exit Sub
End If
End Sub

In this simple example, we simply use the IsNumeric function to verify that the number entered in the changed cell was in fact a number. The first bit of code makes sure that this code applies to all of column A except cell A1. If the user entered a value other than what we want, we alert them and then reactivate the cell for them to enter a correct value. You could change this easily to verify entries as dates, text, etc. You can set this to run when a dropdown is changed and have code conditionally trigger based on the dropdown’s value. Lots and lots of cool ways to interact with a spreadsheet as you change data on it.

Run Code When Worksheet is Activated

Having procedures kick off when a worksheet is activated can be helpful for a variety of reasons. You can refresh SQL queries, pivot tables, or other data sets whenever a worksheet is activated to ensure the user is always looking at the most recent data. For this, you subscribe to the “Worksheet_Activated” event. For this example, I’ll keep it simple for this example and we will simply refresh a pivot table when the worksheet is activated and tell the user that the pivot table was successfully refreshed. If you haven’t read my post on hooking Excel up to SQL queries, you can read it here.

Private Sub Worksheet_Activate()
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
MsgBox "PivotTable is Refreshed"
End Sub

This subroutine will refresh the pivot table each time the user clicks on the sheet where this code is implemented. An additional note here, this event can also be triggered at the workbook level. Stay tuned for an upcoming article on handling workbook level events!

Run Code to Backup Worksheet When Worksheet is Deleted

If you’re using Excel to keep track of records, you may need to ensure that you don’t ever permanently delete data. One approach of doing this is protecting the workbook to prevent any alteration to it. However, I’ve found that many users want the ability to add/delete sheets since they may do quick calculations on a spare sheet and then delete it. If I have a sheet where I need to ensure the data is intact even if the user deletes it, I use the “Worksheet_BeforeDelete” event. The code looks like this:

Private Sub Worksheet_BeforeDelete()
Dim workSheetName As String

workSheetName = ActiveSheet.Name
ActiveSheet.Name = Left(workSheetName, 30) & "@"

ActiveSheet.Copy _
After:=Sheets(ActiveSheet.Index)

ActiveSheet.Name = workSheetName
ActiveSheet.Visible = False

End Sub

This code will capture the sheet name and copy the active sheet to the same spot in the workbook and give it the same name as previous when it detects a delete worksheet event. Lastly it will hide the tab so that the user will not be aware what you’ve done. Formulas and links will be broken to the tab that was deleted but at least you’ll be able to recover any data you might need from the file after the mistake.

Run Code When User Double Clicks

This worksheet event is another one of my favorites. It can be used to make some pretty interactive templates and reports. This particular event is triggered using “Worksheet_BeforeDoubleClick”. It can be used similarly to a hyperlink to help navigate a report, help a user markup a sheet faster, or event navigate to a website. I’ll briefly cover my favorite use of this event subscriber. That is to use it as a “drill-down” action on reports. Often, users want the ability to drill down like you can in a pivot table but a pivot table may not make sense for your dashboard. Let’s assume we have a sales dashboard for a handful of regions that looks like this:

run code when cell values change

Many reviewers of this report might want to look how each store is doing in the region but providing all that context on one sheet is bulky and ugly. You could hyperlink each cell to another sheet and that would work just fine. However, I tend to avoid hyperlinks because they’re “one click actions”. The user can accidentally click the hyperlink which can get annoying. However, users rarely ever double click on a cell unless they mean to.

The first thing I do in this case is name the range of cells I want the user to interact with. In this case, that is the region names (North, South, East, West). I have chosen to name this range “navRange” in this example. No, by using the following code in a before double click worksheet event, I can effectively create a drill down of each region.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
If Not Intersect(Target, Range("navRange")) Is Nothing Then
    Worksheets(Target.Text).Activate
    Cancel = True
End If

End Sub

This snippet simply navigates to the worksheet that is named the same as the cell the user double clicks on. This means that the tabs need to be named the same as the cells the user is double clicking on. Lastly, the Cancel = True line is very important. This is a “BeforeDoubleClick” event which means this code was technically triggered before Excel registered the double click. That means we need to cancel this action or we will end up inside that cell trying to edit the value. The result looks like this:

run code when cell values change

I hope you found this brief introduction on how to run code when cell values change and other worksheet events useful. I plan to follow up with some more advanced stuff soon so stay tuned! If you have any questions over these or any of the worksheet events I did not cover, please drop them in the comments below. As always, you can get the file and code I went over today in the Example Files section of my site.

Cheers,

R

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.

Содержание

  1. Worksheet.Change event (Excel)
  2. Syntax
  3. Parameters
  4. Return value
  5. Remarks
  6. Example
  7. Support and feedback
  8. Событие Worksheet.Change (Excel)
  9. Синтаксис
  10. Параметры
  11. Возвращаемое значение
  12. Замечания
  13. Пример
  14. Поддержка и обратная связь
  15. VBA Excel Worksheet.Change Event
  16. VBA Excel Worksheet_Change Event
  17. How to insert Excel Worksheet_Change Event
  18. Example of Excel Worksheet_Change Event
  19. Trigger Macro when Value Changes
  20. Question
  21. Worksheet Change and SelectionChange Events
  22. Worksheet_Change event procedure
  23. Monitor changes made to specific cell or range
  24. Worksheet_Change Vs. Worksheet_Calculate
  25. Worksheet_SelectionChange event procedure
  26. Take some action when specific cells or ranges selected
  27. How to Tell if a Cell Changed with VBA
  28. What is aВ Worksheet_Change Event?
  29. How do I use this Event?
  30. How do IВ check if the Cell Changed within a Specific Range?
  31. How to avoid infinite loops

Worksheet.Change event (Excel)

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

Syntax

expression.Change (Target)

expression A variable that represents a Worksheet object.

Parameters

Name Required/Optional Data type Description
Target Required Range The changed range. Can be more than one cell.

Return value

Nothing

This event does not occur when cells change during a recalculation. Use the Calculate event to trap a sheet recalculation.

Example

The following code example changes the color of changed cells to blue.

The following code example verifies that, when a cell value changes, the changed cell is in column A, and if the changed value of the cell is greater than 100. If the value is greater than 100, the adjacent cell in column B is changed to the color red.

The following code example sets the values in the range A1:A10 to be uppercase as the data is entered into the cell.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

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

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

Синтаксис

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

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

Параметры

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

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

Nothing

Замечания

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

Пример

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

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

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

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

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

Источник

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.

Источник

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:

Источник

How to Tell if a Cell Changed with VBA

There are times when you want to run a macro when a cell changed. Maybe you want to do some special calculation when a cell changes. Or maybe you’d like to change the font to all uppercase. Or maybe you want to present your users with more meaningful data validation messages. Whatever the case may be, you can use Excel’s Worksheet_Change event in VBA to help accomplish your automation needs.

What is aВ Worksheet_Change Event?

The Worksheet_Change event is a special event that happens in Excel when a cell (or multiple cells) has changed in a specific worksheet. ThisВ includes when a cell is created, updated, or deleted.

This does not include changes like:

  • Formatting changes (font size, cell size, font/cell color, conditional formatting, etc.)
  • A cell changedВ because the calculation was updatedВ (this is a different event called theВ Worksheet_Calculate event)
  • Selecting a cell (this is another event called Worksheet_SelectionChange event)

Does this article help you? If so, please consider supporting me with a coffee ☕️

How do I use this Event?

Open up the VB Editor ( Alt+F11 in Windows or Tools->Macros->Visual Basic Editor on Mac). In the Project window, you’ll see where the workbook and worksheets are:

Double-click on the Sheet1 object and pasteВ the following code:

This is a very basic example of how to start using the Worksheet_Change event. This method is what’s called an Event Handler, which simply means that “this is the method I want to use for handling when X event happens.”

Whenever a cell changes as we described above,В Excel will execute theВ Worksheet_Change event and pass in the cells that were changed through the target object. We use this target object to take a look at which cells were affected.

To invoke this event, go to the Sheet1 worksheet and make a change to a cell. Then, in the VBE Immediate Window ( Ctrl+G on Windows or in Mac this window should always be visible) you will see some text appear each time the event is fired. Here’s an example:

Notice that whenever I change a cell, the Immediate Window shows some text based on the cell I changed. Also note that if I change multiple values at the same time, like cells A1:A2 , then the target object contains that specific range and not just a single cell or array of cells.

It’s important to note that you can work with a range of cells within the same target object that is passed in to the event handler. We’ll take a look at this in the following sections.

How do IВ check if the Cell Changed within a Specific Range?

The target object is simply a range object that describes which cell changed (or set of cells). As shown before, you can get either a single cell, or multiple cells passed into the range (even several range areas, but that’s a topic for another post).

When you want to see if the items that changed fall within another range, you can use the following code:

Here is an example of how this works:

I use the Intersect() function to determine if the target range is within another range that I defined «A1:B3» . The result of Intersect will beВ the range of cells that intersected, if any. The Intersect() function returns Nothing when no intersection is found. ThisВ is why we check for that in the If statement.

Notice that when I select A2:C4 , the target object has the range A2:C4 , but the intersection range has A2:B3 . This is an important distinction to make when working with an intersection. If you used the target range instead of the intersection range, you may end up working with the wrong data (i.e. cells C2:C4 in this case).

How to avoid infinite loops

Now that you know how to monitor changes in your worksheet and act on them, let’s consider what would happen if you make a change to a cell within the Worksheet_Change event.

Consider the following code:

In the For loop, I go through each cell that was effected and prepend the cell with some text.

However, changing the cell value will cause the Worksheet_Change event to fire again, which will take the new value of the text and again prepend it with some more text, and on and on this will go until either Excel crashes or you close the app.

To avoid this, we have to temporarily disable events from firing, make the change to the cell, then re-enable the events.

Application.EnableEvents is a boolean property that you can read / write. When we set this to False , any events that would normally happen (like a Worksheet_Change event) will be suppressed. When we turn this back to True , we will get the events to happen as we expect.

Wow, you read the whole article! You know, people who make it this far are true learners. And clearly, you value learning. Would you like to learn more about Excel? Please consider supporting me by buying me a coffee (it takes a lot of coffee to write these articles!).

Written by Joseph who loves teaching about Excel.

Источник

Понравилась статья? Поделить с друзьями:
  • Excel vba listbox additem
  • Excel vba for financial modeling
  • Excel vba oleobject add
  • Excel vba list of strings
  • Excel vba for eof