EXCEL VBA - 具有多选UserForm列表框的数据输入

时间:2014-09-10 16:31:50

标签: excel vba excel-vba listbox

我正在尝试创建一个用户表单,允许某人选择一些选项并将数据输入我的Excel工作表。在用户表单中,我有一个包含多个答案的列表框。我有它,以便用户可以在列表框中选择多个答案。

如果用户选择2个答案,我希望excel表能够注册2行数据。如果用户选择3个答案,我希望excel表能够注册3行数据。

基本上我正在完成这里描述的内容:http://www.excel-easy.com/vba/userform.html除了“城市偏好”列表框外,我可以选择多个选项。我希望excel表格为所选的每个城市首选项创建一个行项目,同时保持所有其他选择相同。

我认为代码将是这样的:

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

谢谢!

1 个答案:

答案 0 :(得分:2)

使用这样的函数返回所选项目的数组:

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