18.11.2014 Views

Microsoft Office

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Working with Excel Events 43<br />

NOTE<br />

TIP<br />

Sub Setup_OnKey()<br />

Application.OnKey “{PgDn}”, “PgDn_Sub”<br />

Application.OnKey “{PgUp}”, “PgUp_Sub”<br />

End Sub<br />

Sub PgDn_Sub()<br />

On Error Resume Next<br />

ActiveCell.Offset(1, 0).Activate<br />

End Sub<br />

Sub PgUp_Sub()<br />

On Error Resume Next<br />

ActiveCell.Offset(-1, 0).Activate<br />

End Sub<br />

Notice that the key codes are enclosed in brackets, not parentheses. For a complete list of the<br />

keyboard codes, consult the VBA Help. Search for OnKey.<br />

The preceding examples used On Error Resume Next to ignore any errors generated. For<br />

example, if the active cell is in the first row, trying to move up one row causes an error.<br />

Furthermore, if the active sheet is a chart sheet, an error occurs because no such thing as an active cell<br />

exists in a chart sheet.<br />

By executing the following procedure, you cancel the OnKey events, and the keys return to their normal<br />

functions.<br />

Sub Cancel_OnKey()<br />

Application.OnKey “{PgDn}”<br />

Application.OnKey “{PgUp}”<br />

End Sub<br />

Contrary to what you may expect, using an empty string as the second argument for the<br />

OnKey method does not cancel the OnKey event. Rather, it causes Excel to ignore the keystroke<br />

and do nothing. For example, the following instruction tells Excel to ignore Alt+F4 (the percent sign<br />

represents the Alt key):<br />

CAUTION<br />

Application.OnKey “%{F4}”, “”<br />

755

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!