SendKeys doesn't always work

excel, sendkeys, vba

Solution

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

In order to make Excel VBA sleep, I exposed the windows API function `Sleep` by writing at the top of a module:

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

And then after every `SendKeys` command, I just used:

Sleep 1

And literally, 1 millisecond made all the difference and the keys were always sent correctly.

Problem

I am using `.SendKeys()` in Excel VBA to send key strokes to an external window that I am making active using shell `.AppActive` method. The problem is that `SendKeys` is simply not behaving consistently and is sometimes sending the keys and sometimes not. I think it has something to do with storing the keys in the buffer according to MSDN documentation. How does one get around this?

Original source