Tango_Mike
Tango_Mike

Reputation: 104

SENDKEYS Statement fails to execute

I am using the following procedure as part of the OnTime Method:

Public Sub Countdown()
    ThisWorkbook.Activate
    SendKeys ("{ESC}")
    ThisWorkbook.Close False
End Sub

The idea here is to close the workbook, once certain time period elapses; and should the workbook be in an edit mode, the "SendKeys ("{ESC}")" statement should de-activate editing mode. THE PROBLEM IS it does not do that! Once I manually press the "ESC" button, only then does my procedure run. I would greatly appreciate if you could help me understand what I am doing wrong here.

UPDATE: Following @Jeeped recommendation, I have updated the code above by adding the DoEvents line:

Public Sub Countdown()        
    ThisWorkbook.Activate
    SendKeys ("{ESC}")
    DoEvents
    ThisWorkbook.Close False
End Sub

What I have noticed is that this procedure works (while in the editing mode) only if I manually run it by simply pressing the created form control button. Why it is not run as part of the code is something I cannot understand.

Upvotes: 1

Views: 1110

Answers (1)

user4039065
user4039065

Reputation:

Sometimes you need to allow an application to process its message queue. Stick a DoEvents between the SendKeys ("{ESC}") and the ThisWorkbook.Close False.

Public Sub Countdown()
    ThisWorkbook.Activate
    SendKeys ("{ESC}")
    DoEvents
    ThisWorkbook.Close False
End Sub

Upvotes: 3

Related Questions