(Q) How can I interrupt code that's running within a loop through a
keystroke?
(A) You can use GetAsyncKeyState API for this. Here's an
example of a loop that adds n records within a loop and where the code can be interrupted
by pressing the Escape key.
Private Declare Function apiGetAsyncKeyState Lib "user32" _
Alias "GetAsyncKeyState" _
(ByVal vKey As Long) _
As Integer
Private Const VK_ESCAPE = &H1B
Function fBreakInCode()
Dim boolEsc As Boolean
Dim db As Database
Dim rs As Recordset
Dim i As Integer
Set db = CurrentDb
Set rs = db.OpenRecordset("SomeTable", dbOpenDynaset)
For i = 1 To 20000
If apiGetAsyncKeyState(VK_ESCAPE) Then
If MsgBox("You pressed Escape! Do you wish to stop?", _
vbYesNo, "Please confirm") = vbYes Then
Exit For
End If
End If
With rs
.AddNew
!Field1 = i
!Field2 = i * 2
!Field3 = i * 3
.Update
i = i + 1
End With
Next
rs.Close
Set rs = Nothing
MsgBox "Finished. Added " & i & " records!"
End Function
|