【问题标题】:EXCEL VBA - Data Entry with Multi-Selection UserForm List BoxEXCEL VBA - 具有多选用户表单列表框的数据输入
【发布时间】:2014-09-10 16:31:49
【问题描述】:

我正在尝试创建一个用户表单,允许某人选择一些选项并将数据输入到我的 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

谢谢!

【问题讨论】:

    标签: vba excel listbox


    【解决方案1】:

    使用这样的函数返回一个选定项的数组:

    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
    

    【讨论】:

    • 谢谢!我会试试这个,看看它是否有效。第一次来这里,有什么我可以为你做的事吗?
    猜你喜欢
    • 2019-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多