有时 ActiveX Combobox 只显示一行,为什么?

Sometimes the ActiveX Combobox only shows one row, why?

似乎当我先点击组合框然后点击箭头时,所有项目都会显示。

而如果我之前点击箭头而不点击组合框,则只显示一个项目,我可以点击滚动按钮查看其他项目。

为什么会这样?

这是我用来用项目填充组合框的宏

Private Sub ComboBox1_GotFocus()
    Dim c As Range
    Dim selText As String
    selText = ComboBox1.selText
    ComboBox1.Clear
    For Each c In wConfig.Range("BudgetDropdown").Cells
        ComboBox1.AddItem c.Value
    Next c
    ComboBox1.selText = selText
End Sub

要使用命名范围内的数据自动填充组合框,请将其 ListFillRange 属性 设置为范围名称。

你可以在运行时做:

ComboBox1.ListFillRange = "BudgetDropdown"

或者在属性 window 中将其设置为 BudgetDropdown

不知道为什么,但基本上当你打开一个刚刚清除的组合框时,它只显示 1 个通道,因为它 "thinks" 即使你刚刚重新填充它也是空的。要欺骗它,您必须逐一删除所有行,直到达到 ListCount 值(您的组合框将显示的行数)。然后您可以添加所有新行,之后您可以删除之前省略的行。在我的例子中,我无法使用 ListFillRange,因为我的列表在几个单元格中是 "embended";所以我不得不提取它。像这样:

Private Sub Combobox3_GotFocus()

Dim RngRange01 As Range 'Single cell where my row is "embended"
Dim IntCounter01 As Integer 'A counter
Dim BlnCheck as Boolean 'A boolean to remember me if it's the Combobox was empty before i
'focused it

IntCounter01 = ComboBox3.ListCount 'Set the counter equal to ListCount

'I check if the combobox is already filled or not and modify the BlnCheck
BlnCheck = True
If ComboBox3.ListCount = 0 Then BlnCheck = False

'In this For-Next i remove all the rows till i reach the ListRows
For IntCounter01 = IntCounter01 To ComboBox3.ListRows + 1 Step -1
    ComboBox3.RemoveItem IntCounter01 - 1
Next IntCounter01

'Set the range (it's a named list with titles located in another sheet)
Set RngRange01 = Sheets("MySheet1").Cells(2, Sheets("MySheet1").Range("MyList").Column)


Do Until RngRange01.Value = "" 'Cover the whole list

    'This If is to select the right data to insert (originally it was more complicated
    'so i've cut it for this explanation)
    If RngRange01.Offset(0, 1).Value <> RngRange01.Offset(-1, 1).Value Then
        ComboBox3.AddItem RngRange01.Offset(0, 1).Value
    End If

    Set RngRange01 = RngRange01.Offset(1, 0) 'Next cell of the list
Loop

'Now we can remove the rows of the combobox we didn't remove previously (if the combobox 
'wasn't empty already)
If BlnCheck = True then
    For IntCounter01 = ComboBox3.ListRows To 1 Step -1
        ComboBox3.RemoveItem IntCounter01 - 1
    Next IntCounter01
End If

End Sub

到目前为止,只有在您真正第一次聚焦组合框后,它才会起作用。还是很烦人!要完全消除(欺骗)错误,您必须在聚焦之前向组合框添加一些通道;也许当你像这样打开工作簿时:

Private Sub Workbook_Open()

Dim IntCounter01 As Integer 'A counter

IntCounter01 = 1 'Set the counter

'In this For-Next we add a lane till we reach the ListRows
For IntCounter01 = IntCounter01 To Sheets("MySheet2").ComboBox3.ListRows
    Sheets("MySheet2").ComboBox3.AddItem ""
Next IntCounter01

End Sub