

If, at each runtime, the Worksheet_SelectionChange event changes the selection of a cell which itself is part of the Target Range (ie. Recursive Event Loops (though most common in Worksheet_Change events) might happen in Worksheet_SelectionChange events, as in the following example of a recursive loop code:

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

'if any cell in column 1 or 2 is selected If Target.Address = "$A$1" Or Target.Address = "$B$1" Then Exit Sub Increments cell B2 whenever a new cell is selected in column 1 or column 2 (except selection of cells A1 and B1), and if the selected cell is a numeric: If = 1 And IsEmpty(Target) Then = vbBlue Sample Codes for Worksheet_SelectionChange Event:īackground color of a cell(s) changes to blue each time a new selection is made, only if a single and empty new cell is selected: See the Worksheet Change Event in VBA and Preventing Event Loops page for details on using the Target parameter, Error Handlers and to Enable or Disable Events in a code. In this manner, you can limit the events to a particular range for both the Change and SelectionChange events. If Target is not in the defined Range, nothing will happen in the worksheet. If Target is in the defined Range, and when the selection changes within this Range, it will trigger the vba procedure. It refers to the SelectionChange Range and can consist of one or multiple cells. Target is a parameter of data type Range (ie. Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Excel vba on any change code#
You will get a procedure "shell" in the code window as follows: To create a worksheet SelectionChange 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 "SelectionChange" from the right-side "Declarations" drop-down menu. it must be placed in the code module of the appropriate Sheet object. Worksheet SelectionChange procedure is installed with the worksheet, ie. The Worksheet_Change event fires when content in a cell changes, while the Worksheet_SelectionChange event fires whenever a new cell is selected. The selection change event occurs when the selection changes on a worksheet, either by the user or by any VBA application. You can auto run a VBA code, each time that you make a new selection on the worksheet, with the Worksheet_SelectionChange event. Preventing Event Loops with Application.EnableEvents = False Worksheet Change Event in VBA and Preventing Event Loops. Worksheet Selection Change Event in Excel VBA and Preventing Event LoopsĮxcel VBA Events, Event Handler, Trigger a VBA Macro.
