SendKeys并不总是有效

时间:2014-01-10 08:37:50

标签: excel excel-vba sendkeys vba

我在Excel VBA中使用.SendKeys()将关键笔划发送到我使用shell .AppActive方法激活的外部窗口。问题是SendKeys根本不是表现一致,有时发送密钥而有时不发送密钥。我认为这与根据MSDN文档将密钥存储在缓冲区中有关。

如何解决这个问题?

2 个答案:

答案 0 :(得分:4)

您可以考虑使用比SendKeys更可靠的Autoit。

从下方链接下载自动 http://www.autoitscript.com/site/autoit/downloads/

添加参考autoit插件 AutoItX3 1.0类型库

下面是打开计算器并输入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

答案 1 :(得分:3)

我发现解决这个问题的方法是让应用暂停一会儿。这似乎允许缓冲区清除(如果我错了请纠正我)。

为了使Excel VBA睡眠,我通过写在模块顶部来暴露Windows API函数Sleep

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

然后在每个SendKeys命令之后,我只使用了:

Sleep 1

从字面上看,1毫秒完全不同,键总是正确发送。