excel - Excel vba列表框多列多行来自14个文本框
问题描述
我的用户表单有 14 个文本框、2 个命令按钮“下一个”、“发布”和 1 个列表框
我需要代码将数据从 14 个文本框获取到列表框,当用户再次输入新数据并按下一步时,此数据添加到列表框中的第二行,再次获得
最后,当他按下 post 时,所有数据都移动到工作表“数据库”
Sub CommandButton1_Click()
Dim arr1, i As Long
Dim arr2(0 To 0, 0 To 13)
arr1 = Array(TB10, TB10, TB0, tb1, cb1, cb2, tb5, tb4, TB10, TB10, TB10, tb6, tb7, tb8)
For i = 0 To UBound(arr1)
arr2(0, i) = arr1(i)
Next i
ListBox1.List = arr2
End Sub
但此代码仅向列表框添加一次数据,我需要添加更多行♥</p>
解决方案
“...需要添加更多行”
通常,您会将 complete(d) 数据集分配给您的.List
属性ListBox1
(您选择命名它arr2
)。
由于您想增加每个CommandButton1_Click()
事件包含的元素行数并保留所有现有数据,理论上您需要增加二维数组的第一维 - 但使用ReDim Preserve
.
为了克服这个问题,只需反转维度,arr2
从而在其第一个维度中定义您的 14 列值,并将“行”维度定义为第二个维度。列表框控件提供了一个.Column
属性,您可以使用该属性代替通常的.List
属性来写回整个数据集(无需关心有意转置的行和列)。
笔记
当您更改 OP 中的代码时,我假设tb0
, tb1
, ... 对应于枚举的 TextBox 控件。(请根据您的需要更改控件数组中有些奇怪的顺序arr1
。 )
示例代码
Option Explicit ' declaration head of userform code module
Dim arr2() ' make arr2 values disponible for each CommandButton1_Click event
Sub CommandButton1_Click()
' declare/assign variables
Dim arr1(), i As Long, nxt As Long
arr1 = Array(tb0, tb1, tb2, tb3, tb4, tb5, tb6, tb7, tb8, tb9, tb10, tb11, tb12, tb13) ' <~~ Change order to your needs
' define index of next row in listbox
nxt = Me.ListBox1.ListCount ' ListCount automatically counts upper bound + 1
' a) you can only increment an array's last dimension, so ...
' b) redefine arr2 with new elements in its 2nd dimension
ReDim Preserve arr2(0 To UBound(arr1), 0 To nxt)
' assign textbox and combobox values to arr2
For i = 0 To UBound(arr1)
arr2(i, nxt) = arr1(i)
Next i
' reassign arr2 to the listboxes .Column property (instead of the .List property)
ListBox1.Column = arr2
End Sub
Private Sub UserForm_Layout()
With Me.ListBox1
.ColumnCount = 14 ' define column count
.ColumnWidths = "50;50;50;50;50;50;50;50;50;50;50;50;50;50" ' <~~ change to your needs
' .Width = 50 * .ColumnCount + 16
End With
End Sub
请允许我说一句:我认为这回答了你原来的问题。您将找到足够多的示例,如何将数据移回阅读 StackOverflow 站点的工作表,但这需要使用显示您迄今为止尝试过的代码来制定一个新问题 - 请参阅 如何创建最小、完整和可验证的示例.