Home » excel » VBA excel keydetection

VBA excel keydetection

Posted by: admin May 14, 2020 Leave a comment

Questions:

I started with VBA today and I’m making snake.

I have encountered a slight problem: excell doesn’t really have an easy key detection method

what’s the best way of dealing with this problem?

if you are going to answer: use the onkey method:

I can’t make this work because I need a new sub in which I want to give my direction array

(dim direction(2) as integer direction(1) being the x movement direction(2) being the Y movement)

this doesn’t work because the new sub can’t edit another sub’s variables

How could I make that work?

How to&Answers:

The sub KeyTest will test if the QWERTY keys have been pressed.

The sub Finish will stop KeyTest

Public ImDone As Boolean
Public Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer

Sub KeyTest()
    ImDone = False
    Do Until ImDone
        DoEvents
        If (GetAsyncKeyState(vbKeyQ)) Then
            MsgBox "Got a q"
            Exit Sub
        End If
        If (GetAsyncKeyState(vbKeyW)) Then
            MsgBox "Got a w"
            Exit Sub
        End If
        If (GetAsyncKeyState(vbKeyE)) Then
            MsgBox "Got an e"
            Exit Sub
        End If
        If (GetAsyncKeyState(vbKeyR)) Then
            MsgBox "Got an r"
            Exit Sub
        End If
        If (GetAsyncKeyState(vbKeyT)) Then
            MsgBox "Got a t"
            Exit Sub
        End If
        If (GetAsyncKeyState(vbKeyY)) Then
            MsgBox "Got a y"
            Exit Sub
        End If
    Loop
    MsgBox "done"
End Sub

Sub Finish()
    ImDone = True
End Sub

Answer:

More than 3 years later, I am doing a snake as well.

This is how I read the keys so far:

Private Sub ReadKey()

    Select Case True

        Case GetAsyncKeyState(vbKeyUp):
            movingDirection = GoUp

        Case GetAsyncKeyState(vbKeyRight):
            movingDirection = GoRight

        Case GetAsyncKeyState(vbKeyDown):
            movingDirection = GoDown

        Case GetAsyncKeyState(vbKeyLeft):
            movingDirection = GoLeft

    End Select

End Sub