![](/img/trans.png)
[英]How to move Multi Column List line items to another list box along with multi column value excel vba
[英]Excel vba list box multi column multi row from 14 text boxes
我的用戶表單有 14 個文本框、2 個命令按鈕“下一個”、“發布”和 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) 數據集分配給ListBox1
的.List
屬性(您選擇將其命名為arr2
)。
由於您希望通過每個CommandButton1_Click()
事件增加包含的元素行數並保留所有現有數據,因此理論上您需要增加二維數組的第一維 - 但使用ReDim Preserve
不可能的。
為了克服這個問題,只需反轉arr2
維度,從而將您的 14 個列值定義在其第一個維度中,並將“行”維度定義為第二個維度。 列表框控件提供了一個.Column
屬性,您可以使用它代替通常的.List
屬性來寫回整個數據集(無需關心有意轉置的行和列)。
筆記
當您更改 OP 中的代碼時,我假設tb0
、 tb1
、 ... 對應於枚舉的 TextBox 控件。 (請根據您的需要更改控件 Array 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 站點的工作表,但這需要使用代碼來制定一個新問題,其中顯示您迄今為止所嘗試的內容 - 請參閱如何創建最小、完整和可驗證的示例.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.