Excel VBA - 在userform上每隔一次触发alt keydown事件

时间:2015-03-27 17:05:51

标签: excel vba excel-vba

第一次发帖,相当新的VBA和编码。

我有一个Excel 2010用户表单,其中包含一个用于打开电子表格的按钮。我按下按钮创建一个新文件,当按下修改键时。

我写了以下代码:

Private Sub CommandButton4_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Debug.Print "X" & Shift
If Shift = 4 Then
    CommandButton4.Caption = "New File"
    NewFile = True
    CommandButton4.ControlTipText = "New File"
End If
End Sub

Private Sub CommandButton4_KeyUp(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Debug.Print "Y"
CommandButton4.Caption = "Open File"
NewFile = False
CommandButton4.ControlTipText = "Open File"
End Sub

对于每个键EXCEPT Alt,KeyDown和KeyUp事件都会触发。例如,按Shift键,我得到一个调试输出: X1 ÿ X1 ÿ

然而,按Alt我得到: X4 ÿ ÿ X4 ÿ ÿ

我表单中的其他所有内容都能正常运行,但我不知道为什么其他Alt KeyDown都没有注册。没有KeyDown怎么会有KeyUp?

我已经搜索了高低,以获得答案,错误报告或修复,但无法找到答案。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您可以通过API调用轻松解决您的挑战,以检测ALT键是否已关闭。

将其插入新模块

Public Declare Function GetKeyState Lib "user32" (ByVal key As Long) As Integer

试试这个:

Private Sub CommandButton1_Click()
    If GetKeyState(KeyCodeConstants.vbKeyMenu) And &H8000 Then
        MsgBox "Yes"
    Else
        MsgBox "no"
    End If
End Sub

vbKeyMenu是ALT键。 And &H8000只需要查看'live'keystate(返回值有另一个可以打开和关闭的位,请参阅here

修改 您所看到的现象如下:
ALT 并查看X4 Y后,按向下键。 您将看到弹出用户窗体的系统菜单。 alt键遵循它的用途并将焦点移动到系统菜单并返回到下一次按下的按钮。如果按钮具有焦点,则用户窗体显然首先处理按键,并在按钮接收到按键之前将焦点移动到系统菜单。