VBA - close/unwrap/retract 组合框列表?

VBA - close/unwrap/retract a combobox list?

我正在处理一个动态填充的 Excel 组合框(嵌入在工作表中)

但有时当我更新内部列表时它已经 "dropdown/unwrap",显示变得疯狂。

当我填写和检查列表时,我使用这些:

  1. 调整可见行数

    If .ListCount > 14 Then
        .ListRows = 15
    Else
        .ListRows = .ListCount + 1
    End If
    
  2. 到display/unwrap列表(anyCB是我Sub中的一个对象参数)

    anyCB.DropDown
    

但有时,仍然有 15 条可见线,但在大 (15) 条线内有一个小滑块,用于在一条线上滚动所有线...:/

所以我想知道在更改可见行数之前是否有任何方法来close/unwrap/retract列表。关于您可以建议的任何其他解决方法(失去焦点,...);)


以下是我得到的两个奇怪案例的截图:

应该在常规组合框中重现什么:

    For i = 0 To 100
        anyCB.AddItem (i)
    Next i

    With anyCB
        If .ListCount > 14 Then
            .ListRows = 15
        Else
            .ListRows = .ListCount + 1
        End If
    End With
    anyCB.DropDown

    If .ListCount > 0 Then
        For i = .ListCount - 1 To 0 Step -1
            .RemoveItem i
        Next i
    End If
    For i = 0 To 100
        anyCB.AddItem (i)
    Next i
    anyCB.DropDown

这是否与您所看到的相似?

正如您已经提到的,解决方案是在添加项目和调整其 ListRows 之前从 ComboBox 中删除 Focus。

在添加项目和更改 .ListRows

之前尝试调用以下命令
anyButton.SetFocus

一旦你调整了 .ListRows 你就可以调用

anyCB.DropDown

完整的代码示例

anyButton.SetFocus
For i = 0 To 100
    anyCB.AddItem (i)
Next i

With anyCB
    If .ListCount > 14 Then
        .ListRows = 15
    Else
        .ListRows = .ListCount + 1
    End If
End With
anyCB.DropDown

这是一个错误。有两种方法可以解决这个问题

方式一

将值存储在数组中,然后将数组绑定到组合框

Option Explicit

Sub Sample()
    Dim i As Long
    Dim MyAr(100)

    anyCB.Clear

    With anyCB
        '~~> This is required because if you run this
        '~~> procedure for the 2nd time with the dropdown
        '~~> visible then you will face the problem again
        .Activate

        For i = 0 To 100
            MyAr(i) = i
        Next i

        .List = MyAr
        DoEvents
        .DropDown
    End With
End Sub 


方法 2

  1. 致电.DropDown
  2. Select 一个单元格 (Sheeesh!!!)
  3. 再次调用.DropDown

例如

Option Explicit

Sub Sample()
    Dim i As Long

    anyCB.Clear

    With anyCB
        For i = 0 To 100
            .AddItem (i)
        Next i

        If .ListCount > 14 Then
            .ListRows = 15
        Else
            .ListRows = .ListCount + 1
        End If

        .DropDown

        If .ListCount > 0 Then
            For i = .ListCount - 1 To 0 Step -1
                .RemoveItem i
            Next i
        End If

        For i = 0 To 100
            .AddItem (i)
        Next i

        .Activate
        .DropDown
        [A1].Activate
        .DropDown
    End With
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    On Error Resume Next
    If Not Application.Intersect(Target, Me.Range("A1")) Is Nothing Then
        Application.EnableEvents = False
        '~~> Change the selection to another cell, so that it'll work multiple times
        Me.Range("A2").Activate
        Application.EnableEvents = True
        DoEvents
        anyCB.Activate
        Exit Sub
    End If
End Sub