Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Application.OnKey Fails to Reset Properly

Tags:

excel

vba

I am trying to help another user in this forum (reference). The goal is to use the Enter key on the numeric keypad to trigger a macro rather than use the Worksheet_Change event macro for the same purpose.

Before anything is run, both Enter keys work identically. You type stuff in, touch either key, the material gets placed in the cell and Selection moves downward. If you just pump either key, Selection just moves downward.

In a standard module I put:

Sub NumericEnter()
    Application.OnKey "{ENTER}", "InsertIntoTables"
End Sub

and

Sub InsertIntoTables()
    MsgBox "Inserting"
End Sub

After I run NumericEnter(), the Enter key on the numeric keypad calls the proper macro each time it is touched. The normal Enter key is not affected.

I then tried to restore the numeric Enter key by running:

Sub ClearEnter()
    Application.OnKey "{ENTER}", ""
End Sub

The numeric Enter key partially reverts to its original behavior. It no longer calls the macro; it allows data entry into cell, but it does not move Selection at all! (the regular enter key still behaves normally)

I have no idea of what I have missed.

What I have looked at:

  • The normal enter key, the ARROW keys, and the TAB key work just fine at changing Selection
  • Mouse clicking works fine at changing Selection
  • the values of Application.MoveAfterReturn and Application.MoveAfterReturnDirection look fine as well.
like image 788
Gary's Student Avatar asked Jan 31 '18 22:01

Gary's Student


1 Answers

Using just

Application.OnKey "{ENTER}" 

with no second argument seems to clear the macro mapping and return the default key action (Excel 2013)

https://msdn.microsoft.com/en-us/vba/excel-vba/articles/application-onkey-method-excel

expression.OnKey( Key , Procedure )

The description for the Procedure parameter has this:

A string indicating the name of the procedure to be run. If Procedure is "" (empty text), nothing happens when Key is pressed. This form of OnKey changes the normal result of keystrokes in Microsoft Excel. If Procedure is omitted, Key reverts to its normal result in Microsoft Excel, and any special key assignments made with previous OnKey methods are cleared.

like image 198
Tim Williams Avatar answered Nov 09 '22 20:11

Tim Williams