excel - 如何从多选列表框数组(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
解决方案
问题:
- 用于
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
更改工作表名称和范围
演示:
推荐阅读
- reactjs - 安装“sharp”模块出了点问题
- javascript - 如何使用代理合并数组中的相同项目?
- html - 如何使用 Angular 中的 get api 按名字和姓氏搜索?
- reactjs - 如何使用 const 在 .js 中创建一个数组,以便我可以使用该数组来创建一行卡片?
- woocommerce - 自定义 Woocommerce 循环查询
- javascript - 如何将 Element 绑定到不同名称的片段?[SAPUI5]
- antd - 如何在 Antd Table 中将多个数据显示到单个列/单元格中?
- excel - 使用 ActiveCell.Row 时出现类型不匹配错误
- css - 如何在使用 Material UI 的 React 中设置全局字体颜色
- python - TensorFlow 自定义过滤层定义,如 glcm 或 gabor