98.7% Of all customers recommend us, we're so confident about our results we publish all reviews and stats
View Live Stats View ReviewsForum home » Delegate support and help forum » Microsoft VBA Training and help » Using Application.onkey in an if statement | VBA forum
Using Application.onkey in an if statement | VBA forum
Resolved · Medium Priority · Version 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 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
Any suggestions, questions or comments? Please post in the Improve the forum thread. |
VBA tip:Count the Rows and Columns in a SelectionIf you need to count the number of rows or columns in a worksheet use the following code: |