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

时间:2015-06-03 07:02:08

标签: excel vba excel-vba activex

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

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

为什么会这样?

这是我用来填充组合框

的宏
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

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

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

您可以在运行时执行此操作:

ComboBox1.ListFillRange = "BudgetDropdown"

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

答案 1 :(得分:0)

不知道究竟为什么,但基本上当你打开刚刚清除的组合框时,它只显示1个通道,因为它"认为"即使你刚刚补充它也是空的。要欺骗它,您必须逐个删除所有行,直到达到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