I'm on VBA with an apparently simple code, trying to create an event triggered by pressing Enter. So here is my code in the workbook:
Option Explicit
Private Sub Workbook_Open()
Application.OnKey "", "pressEnter"
End Sub
And what should be happen in the module:
Public Sub pressEnter()
ThisWorkbook.Worksheets(1).Cells(1, 1).Value = 20
End Sub
However, when I press Enter/Return key, nothing happens. Just as with a normal Enter, it selects the cell inferior to the active one. I tried with other keys, such as ^+b
or ^+a
, and I have the same problem.
Does someone see any solution ?
You need to specify a key:
Application.OnKey "{ENTER}", "pressEnter"
Application.OnKey "~", "pressEnter"
see Application.OnKey Method (Excel)
Be aware that other keys like ^+b
means ctrl+shift+b. Make sure that Public Sub pressEnter()
is in a module and not in ThisWorkbook
. If it doesn't work in Workbook_Open()
try Workbook_Activate()
instead.