在Excel工作表上填充列表框的第二列+列

时间:2014-10-31 16:17:25

标签: excel vba excel-vba listbox excel-2007

我在Excel 2007工作表上有一个ActiveX列表框。我想直接填充它,而不是将其RowSource属性指向一个范围,因为没有具有所需值的范围。

列表框的ColumnCount设置为2。 我将ColumnWidths设置为“20; 20”,现在它返回: 20 pt; 20 pt

据我了解,列表框中的两列应该可以写,对吗?

填充第一列没有问题:

activesheet.lstApplyCurves.List = array("Select All","Deselect All","aaa","bbb","ccc")

(或)

activesheet.lstApplyCurves.additem
activesheet.lstApplyCurves.List(0,0) = "Col1, Row1"

但是如何填充第2列?我收到错误380(“无法设置列表属性。无效的属性值。”):

activesheet.lstApplyCurves.List(0,1) = "Col2, Row1"

FWIW我也试过这个,但得到同样的错误:

activesheet.lstApplyCurves.List(1,1) = "Col2, Row2"

那么......如何在第二列中设置值?

更新:

除了下面的答案,FWIW我还发现可以为List属性分配多维数组,这更快:

Dim ArrayToListbox() As Variant
ReDim ArrayToListbox(0 To 4, 0 To 2)
ArrayToListbox(0, 0) = "Select All"
ArrayToListbox(1, 0) = "Deselect All"
ArrayToListbox(2, 0) = "Row1-Col1"
ArrayToListbox(2, 1) = "Row1-Col2"
ArrayToListbox(2, 2) = "Row1-Col3"
ArrayToListbox(3, 0) = "Row2-Col1"
ArrayToListbox(3, 1) = "Row2-Col2"
ArrayToListbox(3, 2) = "Row2-Col3"
ArrayToListbox(4, 0) = "Row3-Col1"
ArrayToListbox(4, 1) = "Row3-Col2"
ArrayToListbox(4, 2) = "Row3-Col3" '"(" & Join(Array("a", "b", "c"), "|") & ")"
ActiveSheet.lstApplyCurves.Clear
ActiveSheet.lstApplyCurves.ColumnCount = 3
ActiveSheet.lstApplyCurves.List = ArrayToListbox

1 个答案:

答案 0 :(得分:1)

这对我有用。如果以下内容在您的系统上不起作用,请删除列表框并重新创建,然后再次尝试此代码。

Private Sub CommandButton1_Click()
    With ListBox1
        .Clear
        .ColumnCount = 2

        For i = 1 To 2
            .AddItem
            .List(i - 1, 0) = "Col1, Row" & i
            .List(i - 1, 1) = "Col2, Row" & i
        Next i

    End With
End Sub

enter image description here