如何设置Excel activeX组合框中的项目数



如何在Excel VBA中设置显示activeX组合框的项目数?我尝试这个代码。无论我在第二行设置的数字是多少,都会有默认的8个项目,正如msgbox吐出的那样。

Private Sub ComboBox1_Change()
    ComboBox1.ListRows = 4 'This should work, but it does not
    MsgBox (ComboBox1.ListCount) 'It always equals 8
End Sub

你的代码是"已编码"。

ComboBox1.ListCount给出ListItems的含量

ComboBox1.ListRows = 4设置在你需要开始滚动之前你可以看到的Items的数量的值。

如果你想改变ListItems的数量,你必须改变源代码或使用RemoveItem方法。

参见:List Property, ListCount和ListRows

您需要使用Control对象。这段代码来自https://msdn.microsoft.com/en-us/library/office/ff193982.aspx

Dim ListControl As Control 
 Set ListControl = Forms!Customers!CustomerList 
 With ListControl 
   If .ListCount < 8 Then 
      .ListRows = .ListCount 
   Else 
     .ListRows = 8 
   End If 
 End With 

下面的代码使用这个逻辑,并将它应用到我的Form (UserForm1)组合框(Combobox1)。这又附加到一个按钮单击事件(CommanButton5)。更改J循环中的数字以查看显示的不同行数。注意:这不会改变组合框中的行数,它只是限制了初始下拉框中的行数。您只能通过AddItem/RemoveItem更改组合框中显示的行!

Private Sub CommandButton5_Click()
Dim j As Integer
For j = 0 To 10
  ComboBox1.AddItem j
Next
Me.Repaint
Dim ListControl As Control
 Set ListControl = UserForm1!ComboBox1
 With ListControl
   If .ListCount < 8 Then
       .ListRows = .ListCount
   Else
     .ListRows = 8
   End If
 End With
 Me.Repaint
End Sub

注意:您将不需要Me。如果在窗体初始化事件

中控制此项,则重新绘制

最新更新