ListBox 控件、ColumnCount 和 ColumnWidths 属性示例ListBox control, ColumnCount, ColumnWidths properties example

下面的示例使用**ColumnWidths** 属性更改多列**ListBox** 的列宽。The following example uses the ColumnWidths property to change the column widths of a multicolumn ListBox. 该示例使用三个**TextBox** 控件指定各列的宽度, 并使用**Exit** 事件指定每个textbox的度量单位。The example uses three TextBox controls to specify the individual column widths and uses the Exit event to specify the units of measure of each TextBox. 另请参阅**ColumnCount** 属性。See also the ColumnCount property.

若要使用此示例,请将此示例代码复制到窗体的 Declarations 部分。To use this example, copy this sample code to the Declarations portion of a form. 确保该窗体包含:Make sure that the form contains:

  • A ListBox named ListBox1.A ListBox named ListBox1.
  • Three TextBox controls named TextBox1 through TextBox3.Three TextBox controls named TextBox1 through TextBox3.
  • 一个名为"CommandButton1"的 CommandButtonA CommandButton named CommandButton1.

试着输入 0 值来隐藏列。Try entering the value 0 to hide a column.

Dim MyArray(2, 3) As String 
 
Private Sub CommandButton1_Click() 
 'ColumnWidths requires a value for each column 
 'separated by semicolons 
 ListBox1.ColumnWidths = TextBox1.Text & ";" _ 
 & TextBox2.Text & ";" & TextBox3.Text 
End Sub

Private Sub TextBox1_Exit(ByVal Cancel As _ 
 MSForms.ReturnBoolean) 
 'ColumnWidths accepts points (no units), inches 
 'or centimeters; make inches the default 
 If Not (InStr(TextBox1.Text, "in") > 0 Or _ 
 InStr(TextBox1.Text, "cm") > 0) Then 
 TextBox1.Text = TextBox1.Text & " in" 
 End If 
End Sub

Private Sub TextBox2_Exit(ByVal Cancel As _ 
 MSForms.ReturnBoolean) 
 'ColumnWidths accepts points (no units), inches 
 'or centimeters; make inches the default 
 If Not (InStr(TextBox2.Text, "in") > 0 Or _ 
 InStr(TextBox2.Text, "cm") > 0) Then 
 TextBox2.Text = TextBox2.Text & " in" 
 End If 
End Sub

Private Sub TextBox3_Exit(ByVal Cancel as MSForms.ReturnBoolean) 
 'ColumnWidths accepts points (no units), inches or 
 'centimeters; make inches the default 
 If Not (InStr(TextBox3.Text, "in") > 0 Or _ 
 InStr(TextBox3.Text, "cm") > 0) Then 
 TextBox3.Text = TextBox3.Text & " in" 
 End If 
End Sub

Private Sub UserForm_Initialize() 
Dim i, j, Rows As Single 
 
ListBox1.ColumnCount = 3 
Rows = 2 
 
For j = 0 To ListBox1.ColumnCount - 1 
 For i = 0 To Rows - 1 
 MyArray(i, j) = "Row " & i & ", Column " & j 
 Next i 
Next j 
'Load MyArray into ListBox1 
ListBox1.List() = MyArray 
'1-inch columns initially 
TextBox1.Text = "1 in" 
TextBox2.Text = "1 in" 
TextBox3.Text = "1 in" 
End Sub

支持和反馈Support and feedback

有关于 Office VBA 或本文档的疑问或反馈?Have questions or feedback about Office VBA or this documentation? 请参阅 Office VBA 支持和反馈,获取有关如何接收支持和提供反馈的指南。Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.