How To Exit A Do Or For Loop Using An API Call

This post is going to show you how you can exit a for or do loop in VBA using an API call.

API calls use the power of the Windows operating system to do your wishes.

Here we are using the “GetAsyncKeyState” API function:

Insert the following code in a common module.

Click in the “StopLoop” procedure and press “F5” to run it.

It’s going to try to loop to a million, but when you press “F4”, the program identifies that key as a “stop” key, it “listens” for it, then the loop will be exitted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
'declare virtual key event listener
Private Declare PtrSafe Function GetAsyncKeyState Lib "user32" _
    (ByVal vKey As Long) As Integer
   
'https://georezo.net/jparis/mb_r/dll/pages_user/virtual_key_codes.htm
Private Const VK_F4 = &H73

Sub StopLoop()

    Dim lngCounter As Long
   
    For lngCounter = 1 To 100000000
       
        'exit the loop if certain keystrokes (F4) identified
        If GetAsyncKeyState(VK_F4) Then    ' Send F4 to end loop.
           
            MsgBox "cancel"
            Exit For
           
        Else
            Debug.Print lngCounter
        End If
       
    Next lngCounter
   
    MsgBox "Closing"
   
End Sub

Pretty cool huh?

Next time, I’ll show you how to do this from a button on a form.

Offsite Related Information:

“Go Fund Me” Page


($5 suggested amount)

(…10% of your gift amount will go to charity)

Free! Subscribe To Our YouTube Channel!

Free MS Access VBA Programming Course

Facebooktwitterredditpinterestlinkedinmailby feather
Tags: , , , ,