Excel ActiveX组合框单击事件



我正在尝试在excel中使用ActiveX组合框。一切都很好,可以通过下拉按钮click_event进行填充。但当它设置点击事件时,我发现它甚至是由像箭头键这样的按键触发的。这是正常行为吗?如果是,我该如何绕过它?

我正在使用Excel 2007 VBA

这是我用来允许使用键在组合框中导航的方法,我会等着看是否有更好的解决方案。:lastkey是一个公共变量

Private Sub ComboBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
    If KeyCode = 38 Then
        If ComboBox1.ListIndex <> 0 Then
            lastkey = KeyCode
            ComboBox1.ListIndex = ComboBox1.ListIndex - 1
            KeyCode = 0
        End If
    ElseIf KeyCode = 40 Then
        If ComboBox1.ListIndex <> ComboBox1.ListCount - 1 Then
            lastkey = KeyCode
            ComboBox1.ListIndex = ComboBox1.ListIndex + 1
            KeyCode = 0
        End If
    End If
End Sub
Private Sub ComboBox1_Click()
    If lastkey = 38 Or lastkey = 40 Then
        Exit Sub
    Else
        MsgBox "click"
    End If
End Sub

是的,这是正常行为。使用箭头键导航组合框中的项目,从而触发单击事件。

要绕过它,请插入此代码。这会捕获所有4个箭头键,按下时不会执行任何操作。此方法的唯一缺点是,您将无法再使用箭头键进行导航。

Private Sub ComboBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
    Case 37 To 40: KeyCode = 0
    End Select
End Sub

跟进

Dim ArKeysPressed As Boolean
Private Sub ComboBox1_Click()
    If ArKeysPressed = False Then
        MsgBox "Arrow key was not pressed"
        '~~> Rest of Code
    Else
        ArKeysPressed = False
    End If
End Sub
Private Sub ComboBox1_KeyDown(ByVal KeyCode As _
MSForms.ReturnInteger, ByVal Shift As Integer)
    Select Case KeyCode
    Case 37 To 40: ArKeysPressed = True
    End Select
End Sub

最新更新