SendKeys does not always work

I am using .SendKeys() in Excel VBA to send keystrokes to an external window that I am making active using the shell .AppActive method. The problem is that SendKeys just doesn't behave sequentially and sometimes sends keys, and sometimes not. I think this has something to do with storing keys in a buffer according to the MSDN documentation.

How to get around this?

+6
source share
2 answers

I found that the solution to this problem was to pause the application for a short while. This seems to allow me to clear the buffer (correct me if I am wrong, please).

To hide Excel VBA, I opened the Windows Sleep API function by writing at the top of the module:

 Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long) 

And then after each SendKeys command, I simply used:

 Sleep 1 

And literally 1 millisecond mattered, and the keys were always sent correctly.

+1
source

You can use Autoit, which is more reliable than SendKeys.

Download Autoit from the link below http://www.autoitscript.com/site/autoit/downloads/

Add to the link autoit addin Type Library AutoItX3 1.0

Below is an example of a code that will open a calculator and enter 123456789

 Sub sendkeys() 'Open a calc StartCalculator Dim au As New AutoItX3Lib.AutoItX3 au.AutoItSetOption "WinTitleMatchMode", 2 au.WinActivate "Calculator" 'send key strokes au.ControlClick "Calculator", "", "Button5" au.ControlClick "Calculator", "", "Button11" au.ControlClick "Calculator", "", "Button16" au.ControlClick "Calculator", "", "Button4" au.ControlClick "Calculator", "", "Button10" au.ControlClick "Calculator", "", "Button15" au.ControlClick "Calculator", "", "Button3" au.ControlClick "Calculator", "", "Button9" au.ControlClick "Calculator", "", "Button14" End Sub Sub StartCalculator() Dim Program As String Dim TaskID As Double On Error Resume Next Program = "calc.exe" TaskID = Shell(Program, 1) If Err <> 0 Then MsgBox "Can't start " & Program End If End Sub 

enter image description here

+4
source

All Articles