• Hi All

    Please note that at the Chandoo.org Forums there is Zero Tolerance to Spam

    Post Spam and you Will Be Deleted as a User

    Hui...

  • When starting a new post, to receive a quicker and more targeted answer, Please include a sample file in the initial post.

VBA Code to Run a Macro until press the "F9"

Lasantha

Member
Dear Team,

Could you please give me a VBA code run a specific Macro until we press the "F9" button.

Macro should repeat until we press the "F9" button.

Thank you for your time.
Lasantha.
 
First, I don't know what I'm doing.
Try in a standard code module, right at the top:
Code:
'#If VBA7 Then
#If Win64 Then
Public Declare PtrSafe Function GetAsyncKeyState Lib "USER32" (ByVal vKey As Long) As Integer
#Else
Public Declare Function GetAsyncKeyState Lib "user32" (ByVal vKey As Long) As Integer
#End If

Sub blah()
Const VK_F9 As Long = &H78
xx = Timer + 10    'seconds
Do
  If GetAsyncKeyState(VK_F9) <> 0 Then
    MsgBox "Hello!"
    F9WasPressed = True
    Exit Do
  End If
Loop Until Timer > xx
If Not F9WasPressed Then MsgBox "F9 key was NOT pressed"
End Sub

Notes:
The loop only goes on for 10 seconds (to prevent an endless loop if things don't work).
If during that 10 secs the F9 key is pressed you should get a Hello message, if you don't press F9 you'll get a message that it wasn't pressed.
On my machine the line after the #Else statement was showing in red - it doesn't seem to matter.
The #If VBA7 is something to try if maybe the #If Win64 doesn't work.
Worked here in 64bit Office365.
See attached, click the button which calls blah.
Other key codes can be found here:
or here:

What version of Excel are you using and what bit version?
 

Attachments

  • chandoo48090.xlsx
    398.9 KB · Views: 2
Back
Top