2

我正在尝试在 excel 中使用 ActiveX ComboBox。一切正常,可以从下拉按钮中填充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

1 回答 1

1

是的,这是正常行为。使用箭头键导航组合中的项目,因此会触发 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
于 2012-08-03T09:29:08.750 回答