Search code examples
vbaexcelworksheetxlsm

Worksheet_SelectionChange not working for XLSM worksheet


I am trying to capture a click event in a cell by editing the VBA code in one of my xlsm worksheets. For a sanity check, I am merely trying to turn whatever cell is clicked red. Here is my VBA code

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    'prevent Select event triggering again when we extend the selection below
    Application.EnableEvents = False
    Target.Interior.Color = vbRed
    Application.EnableEvents = True
End Sub

After saving the code, and going back to my worksheet I click on a cell but it doesn't work. I did get this to work in the past at one point, and I'm not sure what I did differently now, but I can't debug the issue.

I'm not sure if this matters, but when I go into the VisualBasic editor, there are multiple projects on the side. I'm only editing the code for a worksheet for the file I'm using, but I can't seem to remove the other project.


Solution

  • The code looks fine (assuming you want to change make every cell you touch turn red), so it must be located in the wrong place.

    1. Reboot your machine. (humour me)

    2. Open Excel and create a new workbook.

    3. Right click the worksheet's tab (at the bottom of the screen) and click View Code.

    4. Paste your code into the worksheet's module that opens.

    5. Click the worksheet.