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

前端 未结 2 1980
庸人自扰
庸人自扰 2020-12-17 06:55

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

相关标签:
2条回答
  • 2020-12-17 07:36

    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

    If I read this correctly, you want a blank row between every user inputted value doing down and a blank column between every user inputted value going 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 occurs for all navigation. If you only want this to occur on input, modify to suit a Worksheet_Change event macro instead of a Worksheet_SelectionChange event macro.

    0 讨论(0)
  • 2020-12-17 07:40

    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}".

    0 讨论(0)
提交回复
热议问题