Change worksheets vba excel

Содержание

  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

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

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.

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

Понравилась статья? Поделить с друзьями:
  • Change word space between lines
  • Change word order online
  • Change word online language
  • Change the plural form word
  • Change word no problem