vba SendKeys 并不总是有效
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21039489/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
SendKeys doesn't always work
提问by rex
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.
我.SendKeys()
在 Excel VBA 中使用将击键发送到我使用 shell.AppActive
方法激活的外部窗口。问题在于它SendKeys
只是行为不一致,有时会发送密钥,有时不会。我认为这与根据 MSDN 文档将密钥存储在缓冲区中有关。
How does one get around this?
如何解决这个问题?
采纳答案by rex
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:
为了让 Excel VBA 休眠,我Sleep
通过在一个模块的顶部编写来暴露 windows API 函数:
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
And then after every SendKeys
command, I just used:
然后在每个SendKeys
命令之后,我只是使用:
Sleep 1
And literally, 1 millisecond made all the difference and the keys were always sent correctly.
从字面上看,1 毫秒使一切变得不同,并且密钥始终正确发送。
回答by Santosh
You may consider using Autoit which is more reliable than SendKeys.
您可以考虑使用比 SendKeys 更可靠的 Autoit。
Download Autoit from below link http://www.autoitscript.com/site/autoit/downloads/
从以下链接下载 Autoit http://www.autoitscript.com/site/autoit/downloads/
Add in reference autoit addin AutoItX3 1.0 Type Library
添加参考 autoit addin AutoItX3 1.0 类型库
Below is sample code which will open the calculator and type 123456789
下面是示例代码,它将打开计算器并输入 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