How to call a function on ENTER key in Excel using vba

puk picture puk · Jul 27, 2016 · Viewed 10.8k times · Source

Google should provide me with ample examples but none of them seem to work

What I want: Everytime the user presses, and then releases, the ENTER key, for my program to do do something (ie. create a MsgBox, or call function Foo). I would prefer this in the form of a MWE

What I have done: I have tried googling it but none of the examples are functional. They compile, but don't do anything. I have also made sure to save in a macro compatible Excel format.

What I am using: I am using Excel 2016, 64 bit with Office 365

EDIT: The user is entering this information into the worksheet. I want to intercept the user input and everytime they press ENTER, take the cursor/active cell down two rows, so there is an empty cell below every cell. If the user presses tab, I want to take the cursor/active cell right two columns, so there si an empty cell to the right of every cell.

EDIT 2: here is a MWE of what I have right now which should work, but which does nothing. I am adding this to the worksheet, and not as a module

Sub SomeActions()
    MsgBox ("Hello")
End Sub

Private Sub Workbook_Open()
    Application.OnKey "~", "SomeActions"
End Sub

Answer

ttaaoossuu picture ttaaoossuu · Jul 27, 2016

First, make an callback Sub that performs the logic you need. Put it into a new code module (NOT into worksheet code):

Sub SomeActions()
...
End Sub

Then, subscribe to OnKey event, for example, when the user opens the workbook (this code goes into ThisWorkbook) module in VBA editor:

Private Sub Workbook_Open()
    Application.OnKey "~", "SomeActions"
End Sub

"~" means Enter key. For numeric keypad key use "{ENTER}".