Excel vba列表框多列多行从14个文本框

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Excel vba列表框多列多行从14个文本框相关的知识,希望对你有一定的参考价值。

我有用户表单,有14个文本框,2个命令按钮“next”,“Post”和1个列表框

我需要代码将数据从14个文本框传送到列表框,再次当用户输入新数据并按下此数据添加到列表框中的第二行时,再次获取

最后当他发布所有数据后移到工作表“数据库”

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

但是这段代码只将一次数据添加到列表框中,我需要添加更多行♥

答案

“......需要添加更多行”

通常,您会将完整的(d)数据集分配给.ListListBox1属性(您选择将其命名为arr2)。

由于您希望使用每个CommandButton1_Click()事件增加包含的元素行数并保留所有现有数据,理论上您需要增加二维数组的第一维 - 但使用ReDim Preserve是不可能的。

要解决这个问题,只需反转arr2的维度,从而在第一维中定义14列值,将“行”维度定义为第二维。列表框控件提供了一个.Column属性,您可以使用该属性而不是通常的.List属性来编写整个数据集(无需关注有意转置的行和列)。

注意

当您在OP中更改代码时,我假设tb0tb1,...对应于枚举的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站点的工作表,但是这需要用代码显示一个新问题,显示您到目前为止所尝试的内容 - 请参阅How to create a Minimal, Complete, and Verifiable example

以上是关于Excel vba列表框多列多行从14个文本框的主要内容,如果未能解决你的问题,请参考以下文章

excel vba 将一个文本框TEXTBOX1限定只能输入数字,如果输入其他汉字或者字母提示,输入错误,请输入数字

VBA Excel - 如何修复列表框表单上的过滤器代码

VBA - Excel列表框 - 在向第二个列表框添加项目时查找重复项

listbox的值怎么获取vba

Excel VBA在IE11中使用自动完成填充文本框

Excel VBA文本框以填充组合框