列表框错误" Could not Set the List property. Invalid Property Value."



我有一个带有列表框、文本框、组合框和保存按钮的userform。下面是我的保存按钮代码。

Private Sub cmdsave_Click()
Dim x As Integer
x = Me.ListBox1.ListCount
If Me.cmbtrans.Value = "Debit" Then
With Me.ListBox1
.Enabled = True
.ColumnCount = 13
.ColumnWidths = "49.95 pt;10 pt;114.95 pt;10 pt;114.95 pt;10 pt;114.95 pt;10 pt;75 pt;10 pt;49.95 pt;10 pt;49.95 pt"
.AddItem
.List(x, 0) = Me.txtdate
.List(x, 1) = "|"
.List(x, 2) = Me.txtgrouphead
.List(x, 3) = "|"
.List(x, 4) = Me.txtcontrolhead
.List(x, 5) = "|"
.List(x, 6) = Me.cmbaccounthead
.List(x, 7) = "|"
.List(x, 8) = Me.cmbtrans
.List(x, 9) = "|"
.List(x, 10) = Me.txtamount
End With
End If
End Sub

它显示了添加项目级别.List(x, 10) = Me.txtamount的错误。但是,它平稳地运行,直到添加项目级别.List(x, 9) = "|"

我不明白它为什么在最后一行出错。

克服10列限制的数组方法

.AddItem方法有一个限制和默认设置,即只能在列表框(或组合框)中创建10列List索引是从零开始的,最多只能加上.List(x, 9)

如果要克服此内置限制,必须使用Array方法,该方法允许在一条语句中将整个数组分配给.List属性。

当您在每次事件单击时增加列表框行元素以添加新的控件值时,您必须通过一个新行元素重新确定整个数据集的尺寸。

然而,ReDim Preserve语句只能在其最后一个维度中执行。因此,您必须使用一个二维数组,其中"行"索引紧跟在不变的"列"索引之后,才能提供一个尺寸正确的数组。

技巧:您可以使用已经接受反转(=转置)维度顺序的.Column属性,而不是重新转换此数组并将其分配回listboxes.List属性。

示例代码

为进一步方便起见,添加了一个控件名称字符串,因为它允许通过Controls集合获取循环中使用的控件值,该集合允许按名称引用它们。

Private Sub cmdSave_Click()
' Define a control names string to be used to append to Listbox1
Const USEDCONTROLS$ = "txtdate,txtgrouphead,txtcontrolhead,cmbaccounthead,cmbtrans,txtamount"
Dim x&, i&, v, myCtrls
myCtrls = Split(USEDCONTROLS, ",")        ' create flat array myCtrls out of control names
x = Me.ListBox1.ListCount                 ' get current list count
If Me.cmbtrans.value = "Debit" Then
With Me.ListBox1
.Enabled = True
.ColumnWidths = "49.95 pt;10 pt;114.95 pt;10 pt;114.95 pt;10 pt;114.95 pt;10 pt;75 pt;10 pt;49.95 pt;10 pt;49.95 pt"
.ColumnCount = 13
If .ListCount > 0 Then
' [1] write existing listbox elements to array(column index, row index)
v = .Column
' [2] increment to new row index x in 2nd (sic!) dimension
'     as a ReDim Preserve can only change the last array dimension.
'     (with the .Column property you are using the
'     transposed counterpart of the .List property)
ReDim Preserve v(UBound(v), x)
Else
' [1-2] redimension array v the first time (no existing listbox values so long)
ReDim v(.ColumnCount - 1, 0)           ' 13 counted columns equal a zerobased index of 12
End If
' [3a] assign current values to array
For i = 0 To UBound(myCtrls)
v(i * 2, x) = Me.Controls(myCtrls(i))
Next i
' [3b] write separators after each data input
For i = 1 To UBound(v) - 1 Step 2: v(i, x) = "|": Next i
' [4] reassign array to listbox property .Column (~ transposed .List property)
.Column = v
End With
End If
End Sub

相关内容

最新更新