简体   繁体   中英

Worksheet_SelectionChange not performing desired task

Background:

I don't appear to know what I'm doing with SelectionChange and would like some help to ensure I'm using it correctly.

I have right-clicked This Workbook , in the VBA window, and selected View Code . I have my code in that field. In the immediate window (ctrl+g), I have input:

Application.EnableEvents=True

Code:

The code I'm using to test is supposed to display the target row/column in a cells(1,1):

Option Explicit

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim r, c As Integer
    If Selection.Count = 1 Then
        c = Target.Column
        r = Target.Row
        Cells(1, 1).Value = "Cells(" & r & ", " & c & ")"
    End If
End Sub

Question:

Am I missing something to enable the selection change event?

If you right click on ThisWorkbook and select View Code you will see two dropdowns above the code window. The leftmost allows you to select (General) or Workbook . If you select Workbook, the rightmost dropdown will provide all the events you can utilise at the Workbook level. Worksheet_SelectionChange is not there as it's not a Workbook level event.

Workbook level events include events like Open , Close and SheetChange . Note: SheetChange fires when the user changes the sheet selected, not makes a change to a given sheet.

If you do the same but with the Sheet1 (Sheet1) object, the leftmost dropdown will show (General) and Worksheet . Selecting this will provide the events available at the Worksheet level. Pick SelectionChange and the VBE will automatically create the shell of the event ready for you to populate with your code.

Note, this event will only fire if a cell is changed on the sheet you've added the code to so keep this in mind when creating your event(s).

不要右键单击ThisWorkbook ,而是右键单击Sheet1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM