How to call function on ENTER key in Excel using vba

Google should provide me with many examples, but none of them work.

What I want: Each time the user presses and then releases the ENTER key, my program does something (i.e. creates an MsgBox or a call function Foo). I would prefer this in the form of MWE

What I did: I tried using it, but none of the examples work. They compile but do nothing. I also saved in macro compatible Excel format.

What I use: I use Excel 2016, 64 bit with Office 365

EDIT: The user enters this information into the worksheet. I want to intercept user input, and each time they press ENTER, move the cursor / active cell two lines, so there is an empty cell under each cell. If the user clicks on the tab, I want to take the cursor / active cell to the right two columns, so there is an empty cell to the right of each cell.

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

Sub SomeActions() MsgBox ("Hello") End Sub Private Sub Workbook_Open() Application.OnKey "~", "SomeActions" End Sub 
+1
source share
2 answers

First make a Sub callback that will execute the required logic. Put it in the new code module (NOT in the worksheet code):

 Sub SomeActions() ... End Sub 

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

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

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

+1
source

What I want: every time the user presses and then releases the ENTER key, my program does something (i.e. creates an MsgBox or a call function Foo).
I would prefer it in the form of MWE

If I read this correctly, you need an empty row between each user entered value and an empty column between each user entered value going to the right.

On the worksheet code sheet:

 Option Explicit Private Sub Worksheet_SelectionChange(ByVal Target As Range) If Target.Count > 1 Then Exit Sub Application.EnableEvents = False Dim r As Long, c As Long If Target.Row / 2 <> Int(Target.Row / 2) Then r = 1 If Target.Column / 2 <> Int(Target.Column / 2) Then c = 1 Target.Offset(r, c).Activate Application.EnableEvents = True End Sub 

This happens for all navigation. If you want this to happen at the input, change the event macro instead of Worksheet_SelectionChange according to Worksheet_Change .

+1
source

Source: https://habr.com/ru/post/1275128/


All Articles