EXCEL VBA – 具有多选用户窗体列表框的数据input
我试图创build一个用户表单,允许某人select一些选项并将数据input到我的Excel表单中。 在用户表单中,我有一个列表框,有几个答案。 我拥有它,以便用户可以在列表框中select多个答案。
如果用户select2个答案,我希望Excel表格登记2行数据。 如果用户select3个答案,我想让Excel表格登记3行数据。
基本上我正在做什么在这里描述: http : //www.excel-easy.com/vba/userform.html除了在“城市偏好”列表框,我可以select多个select。 我希望Excel表格为每个城市偏好select创build一个项目,同时保持所有其他select。
我在想代码会是这样的:
For i = 1 to "total # of items selected in listbox" emptyrow = WorksheetFunction.CountA(Range("A:A")) + 1 Worksheet.Cell(emptyrow,3).Value = "Selected item(i) from list box" Next I
谢谢!
使用这样的函数返回一个选定项目的数组:
Public Function GetSelectedItems(lBox As MSForms.ListBox) As Variant 'returns an array of selected items in a ListBox Dim tmpArray() As Variant Dim i As Integer Dim selCount As Integer selCount = -1 For i = 0 To lBox.ListCount - 1 If lBox.selected(i) = True Then selCount = selCount + 1 ReDim Preserve tmpArray(selCount) tmpArray(selCount) = lBox.List(i) End If Next If selCount = -1 Then GetSelectedItems = Array() Else: GetSelectedItems = tmpArray End If End Sub
然后修改你的代码:
Dim selectedItems as Variant selectedItems = GetSelectedItems(myListBox) 'Modify this line to refer to your listbox name For i = lBound(selectedItems) to UBound(selectedItems) emptyrow = WorksheetFunction.CountA(Range("A:A")) + 1 Worksheet.Cell(emptyrow,3).Value = selectedItems(i) Next