首页 > 解决方案 > 如何从多选列表框数组(VBA)中正确检索每个选定的值

问题描述

我有一个多选列表框,当更新 cbo 框(选择出借人的名称)时,该列表框填充有连接值(由出借项目的项目 ID 号和项目名称组成)。

本质上,我希望能够回忆或参考每个选定列表项的第一个串联值。以下代码是我尝试将列表框的值保存在数组中,同时尝试仅调用每个选择的第一个串联值。

此代码起作用,但由于某种原因,它只调用最后选择的值。例如,如果选择了以下列表框项;"1:Anthropometric Tape Measure"然后"2:Anthropometric Measuring Kit"报告的值(在用于故障排除的 msgbox 中)是"2,2"IF 最后选择第二项,而不是"1,2".

奇怪的是,如果我使用数组代码而不只引用第一个连接值,(tmpArray(selCount) = lbox.List(i)而不是Split(lbox.List(lbox.ListIndex), ":")(0))代码会正确运行。

任何有关解决此问题的建议将不胜感激,谢谢!

Public Function GetSelectedItems(lbox As Object)

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) = Split(lbox.List(lbox.ListIndex), ":")(0)
        End If
    Next

    If selCount = -1 Then

        GetSelectedItems = ""
    Else:
        GetSelectedItems = Join(tmpArray, ", ")
    End If

End Function

我正在使用以下代码将数组召回到消息框(仅供参考)。

Dim mySentence As String

mySentence = GetSelectedItems(Me.ListItem)

  Msg = "You selected" & vbNewLine & mySentence

标签: excelvba

解决方案


问题:

  • 用于Lbox.ListIndex

回答:

  • 而是必须使用i. 以上参考了单选列表框中的选定项。我将在多项选择中给出所选项目的正确索引。

代码:

Public Function GetSelectedItems(lbox As Object)

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) = Split(lbox.list(i), ":")(0)

            Set fnd = Worksheets("Sheet7").Range("B11:B19").Find(Split(lbox.list(i), ":")(0))

            If Not fnd Is Nothing Then

                  fnd.Offset(0, 1).Value = "Selected"

            End If


        End If
    Next

    If selCount = -1 Then

        GetSelectedItems = ""
    Else:
        GetSelectedItems = Join(tmpArray, ", ")
    End If

End Function

更改工作表名称和范围

演示:

在此处输入图像描述


推荐阅读