Excel VBA Detect A KeyPress Only When Cell In A Certain Range Is Selected

103 Views Asked by At

I have a spreadsheet and I would like to use KeyPress to detect if the user presses 1, 2, 3 or 4 keys. I have a range on my sheet that is 10 cells by 20 cells and I only want to KeyPress event to work when they have a cell in that range selected. Anywhere outside that range, I would like the KeyPress event to do nothing.

Thank you

I could find examples of how to use KeyPress, but no examples of how to detect the keys ONLY when the user has a cell selected within a certain range of cells.

Thank you

1

There are 1 best solutions below

0
Lord-JulianXLII On

You can have it so keys are always detected, but the code that is called on detection has a condition that will only continue the execution if your selection is in the Range

The Keypress will call a Sub.

Just have that Sub check if the current Selection Intersects with your Range and exit the Sub / do nothing if it doesn't.

So smth. like

Sub onKeyPress()
    If Selection Intersects Range Then
        'do whatever you want to do here
    End If
End Sub

* This is not valid VBA - it is just to show the concept