Wednesday, November 26, 2014

Disabling Keys in Excel

Some one asked if there is a way to disable the F1 or any other key in Excel. 
The only way to disable a key such as this is to create a macro. The following macro will do the trick quite nicely to disable the F1 key:
Private Sub Workbook_Open()
    Application.OnKey "{F1}", ""
End Sub
Private Sub Workbook_BeforeClose(CANCEL As Boolean)
    Application.OnKey "{F1}"
End Sub
Actually, there are two macros here. The first one executes whenever the workbook is opened, and the second is executed when the workbook is closed. In the case of the first macro, the OnKey method traps every keypress of F1and cancels it. The macro that runs when the workbook closes restores the normal operation of the F1 key.
These macros can be placed in a given workbook, in which case they will only apply while that workbook is open. If you want them to apply at all times when using Excel, store the macros in the Personal workbook.

You can replace the {F1} with any key of your choice.
For key arguments see Keys Arguments and Key Combinations

Keys and Key Combinations

Keys and Key Combinations

For the Keys argument, you can use keys or key combinations. You can type a character, such as "a" or use codes from the table below:
Key
Code
BACKSPACE
{BACKSPACE} or {BS}
BREAK
{BREAK}
CAPS LOCK
{CAPSLOCK}
CLEAR
{CLEAR}
DELETE or DEL
{DELETE} or {DEL}
DOWN ARROW
{DOWN}
END
{END}
ENTER (numeric keypad)
{ENTER}
ENTER
~ (tilde)
ESC
{ESCAPE} or {ESC}
HELP
{HELP}
HOME
{HOME}
INS
{INSERT}
LEFT ARROW
{LEFT}
NUM LOCK
{NUMLOCK}
PAGE DOWN
{PGDN}
PAGE UP
{PGUP}
RETURN
{RETURN}
RIGHT ARROW
{RIGHT}
SCROLL LOCK
{SCROLLLOCK}
TAB
{TAB}
UP ARROW
{UP}
F1 through F15
{F1} through {F15}
To combine keys with Ctrl, Shift and/or Alt, precede the character with the following codes. For example:
SendKeys "^{F2}"   ...for Ctrl+ F2


Key
Code
SHIFT
+ (plus sign)
CTRL
^ (caret)
ALT
% (percent sign)