Excel ActiveX ComboBox onClick事件

时间:2012-08-03 08:48:00

标签: excel vba excel-vba excel-2007 activexobject

我正在尝试在Excel中使用ActiveX ComboBox。一切正常,从下拉按钮click_event填充。但是当它设置click事件时,我发现它甚至可以通过箭头键等按键触发。这是正常的行为,如果是这样,我该如何绕过这个?

我正在使用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

1 个答案:

答案 0 :(得分:0)

是的,这是正常行为。使用箭头键导航组合中的项目,因此触发了click事件。

绕过插入此代码。这会捕获所有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