简体   繁体   中英

VBA: application.onkey not working

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:

  • For Enter on the numeric keypad use Application.OnKey "{ENTER}", "pressEnter"
  • For the normal Enter use 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM