Public Schedule Face-to-Face & Online Instructor-Led Training - View dates & book

using applicationonkey if statem

Forum home » Delegate support and help forum » Microsoft VBA Training and help » Using Application.onkey in an if statement

Using Application.onkey in an if statement

ResolvedVersion 2003

Alex has attended:
Excel VBA Intro Intermediate course
Excel VBA Advanced course

Using Application.onkey in an if statement

Option Explicit
Dim bCancelPressed As Boolean
Private Sub Commandbutton1_Click()
bCancelPressed = False
Dim x As Integer
x = 1

Do While bCancelPressed = False


Selection.Cut
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Selection.Name = ("mycell")

DoEvents
Application.Wait Now + TimeSerial(0, 0, 0.6)
Loop
End Sub


What i want to do is end the loop when the right key is pressed. I am using application.onkey to detect the whether the key has been pressed and that works fine outside the loop.

This is what i want to happen

If Appliction.onkey = Right Then
Exit Do
End If



Thanks

RE: Using Application.onkey in an if statement

Hi Alex, thanks for your query. The Onkey method does have its limitations and ideally you should be making a call to the Windows API in order to capture any keyboard input. The following code should do what you want:

***************

Option Explicit
Dim bCancelPressed As Boolean
Declare Function GetKeyState Lib "user32" (ByVal nVirtKey As Long) As Integer
Const VK_LEFT As Integer = &H25 'left

Sub test()
bCancelPressed = False
Dim x As Integer
Dim leftpressed As Boolean

x = 1

Do While bCancelPressed = False

Selection.Cut
Selection.Offset(1, 0).Select
ActiveSheet.Paste
Selection.Name = ("mycell")

If GetKeyState(VK_LEFT) < 0 Then leftpressed = True Else leftpressed = False
If leftpressed = True Then
bCancelPressed = True
Else
bCancelPressed = False
End If

DoEvents
Application.Wait Now + TimeSerial(0, 0, 0.6)
Loop

MsgBox "Stopped"

End Sub

*******************

Hope this helps,

Anthony

Mon 8 Mar 2010: Automatically marked as resolved.

 

Training courses

Training information:

Welcome. Please choose your application (eg. Excel) and then post your question.

Our Microsoft Qualified trainers will then respond within 24 hours (working days).

Frequently Asked Questions
What does 'Resolved' mean?

Any suggestions, questions or comments? Please post in the Improve the forum thread.

VBA tip:

Suspend DisplayAlerts in VBA

To stop Excel asking you things like "Do you want to delete this file...", use the following line of code at the beginning of the relevant VBA procedure:

Application.DisplayAlerts = False

At the end of the procedure make sure you use the following code to reactivate Display Alerts:

Application.DisplayAlerts = True

View all VBA hints and tips

Connect with us:

0207 987 3777

Call for assistance

Request Callback

We will call you back

Server loaded in 0.12 secs.