excel 在用户表单中处理智能组合框

14ifxucb  于 2023-10-22  发布在  其他
关注(0)|答案(1)|浏览(97)

我发现了这个智能代码,当你输入名字的时候,它会列出点击率,就像一个快速搜索。一切正常,但如果我单击组合框旁边的箭头并从列表中选择某些内容,我必须在它触发之前按回车键。我希望它运行我的“viewProject”时点击。其次,一个额外的好处是,如果活动工作表上的列表包含的对象少于3个,代码就会出错。我做了一个快速修复,使一个空间,如果这将accure。有更好的办法吗?谢谢你的帮助!

Option Explicit

Private Comb_Arrow As Boolean

Private Sub ComboBox1_Change()
Dim i As Long
If ActiveSheet.Cells(2, 2) = "" Then ActiveSheet.Cells(2, 2) = " "
If ActiveSheet.Cells(3, 2) = "" Then ActiveSheet.Cells(3, 2) = " "
If Not Comb_Arrow Then
    With ComboBox1
        .List = ActiveSheet.Range("B2", Cells(Rows.count, 2).End(xlUp)).value
        .ListRows = Application.WorksheetFunction.Min(4, .ListCount)
        .DropDown
        If Len(.text) Then
            For i = .ListCount - 1 To 0 Step -1
                If InStr(1, .List(i), .text, vbTextCompare) = 0 Then .RemoveItem i
            Next
            .DropDown
        End If
    End With
End If
End Sub

Private Sub ComboBox1_KeyDown(ByVal KeyCode As MSForms.ReturnInteger, ByVal Shift As Integer)
Comb_Arrow = (KeyCode = vbKeyUp) Or (KeyCode = vbKeyDown)
If KeyCode = vbKeyReturn Then
    With ComboBox1
        If .ListIndex = -1 And .LineCount > 0 Then
            .ListIndex = 0
        End If
        .List = ActiveSheet.Range("B2", Cells(Rows.count, 2).End(xlUp)).value
        If .ListIndex > -1 Then
            Call viewProject
        End If
    End With
End If
End Sub
jexiocij

jexiocij1#

你现在可能已经找到了解决方案,但对于未来的读者(可能你仍然),这里是:
你的.List抛出的错误不是3行,而是2行(因为你从B2开始查找),如果你让B3为空,那么只有一个值被赋予.List,而它需要一个数组。Range(“B2”).Value =仅为Range(“B2:B3”)时的值。Value为数组。
对于单击,通常可以使用Click事件:

Private Sub ComboBox1_Change()
    Dim i As Long
    Dim rng As Range: Set rng = ActiveSheet.Range("B2", Cells(Rows.Count, 2).End(xlUp))
    If rng.Count < 2 Then Set rng = rng.Resize(2) 'get the empty cell beneath it as well
    If Not Comb_Arrow Then
        With ComboBox1
            .List = rng.Value
            .ListRows = Application.WorksheetFunction.Min(4, .ListCount)
            .DropDown
            If Len(.Text) Then
                For i = .ListCount - 1 To 0 Step -1
                    If InStr(1, .List(i), .Text, vbTextCompare) = 0 Then .RemoveItem i
                Next
                .DropDown
            End If
        End With
    End If
End Sub

Private Sub ComboBox1_Click()
    viewProject 'this should only run your macro when selecting a list item
End Sub

相关问题