Search code examples
vbaexcelkeyup

Fire events when key is released VBA


I have this code to detect when Enter is pressed

Private Declare Function GetKeyState Lib "user32" _
(ByVal nVirtKey As Long) As Integer
   Const VK_RETURN As Integer = &HD

And I use this function in a macro like this

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
   If GetKeyState(VK_RETURN) < 0 Then Enter = True Else Enter = False
   If Enter = True Then
       Call IncreaseValue
   End If
End Sub

This however is called multiple times when the Enter key is held down. Is there a way to only call this function once every time the enter key is pressed?

Additional info just in case: Why I need it is because I have a dataentry sheet, which works as a form - every time the enter key is pressed, it increases a cell value by 1, which is used to lookup values. But holding down enter will skip through records.


Solution

  • Of course there's! All you need is to track Enter key toggling (note return values).

    The main idea behind that is to track the low-order bit (toggle/untoggle), and whenever it changes and the high-order bit is 1 (pressed) - we're free to increase what we desire.

    Private Sub Worksheet_SelectionChange(ByVal Target As Range)
        Static StatePreservedResponse As Long
        Dim StateResponse As Long
    
        StateResponse = GetKeyState(VK_RETURN)
    
        If StateResponse < 0 And StateResponse <> StatePreservedResponse Then
            Call IncreaseValue
        End If
    
        StatePreservedResponse = StateResponse
    End Sub