使用listbox multiselect从列表返回多个索引时出错
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用listbox multiselect从列表返回多个索引时出错相关的知识,希望对你有一定的参考价值。
VBA的新手,有点沮丧。试图为我的老师们制作一份表格来简化文书工作。
我有一个表格1. apple 橙色 葡萄
如果用户要从列表中选择apple和grape,我希望单元格只包含索引。所以在单元格中打印(1,3)。我不想要这些话。
我目前的代码
Private Sub SpedAccomAddBtn_Click()
'variable to count multiple selections'
VarSped = " "
'loop to keep track of indexes of selected items'
For X = 0 To Me.SpedListBx.ListCount - 1 'count through list
If Me.SpedListBx.Selected(X) Then
If VarSped = " " Then 'if blank then record first item'
VarSped = Me.SpedListBx.ListIndex + 1 'first selected item. +1 because excel is a 0 based index'
Else 'if not the first selection add a , between selections'
VarSped = VarSped & "," & Me.SpedListBx.ListIndex + 1
End If
End If
Next X
ThisWorkbook.Sheets("Master SPED Sheet").Range("c4") = VarSped 'print to cell'
如果我使用前面选择Apple和Grape的例子,我得到(3,3)不是(1,3)。我无法弄清楚为什么VarSped会被覆盖。 (我是编码的新手,我必须评论一切,所以我觉得我知道我在做什么)
答案
你的循环迭代器已经是你的项目位置:只需添加一个来管理基于0的列表:
Option Explicit
Private Sub SpedAccomAddBtn_Click()
Dim VarSped As String ' a string is always initialized with a null string, i.e. with a "" string. hence no need for a 'VarSped = ""' statement
Dim X As Long
For X = 0 To Me.SpedListBx.ListCount - 1 'count through list
If Me.SpedListBx.Selected(X) Then VarSped = VarSped & "," & X + 1
Next
If VarSped <> vbNullString Then ThisWorkbook.Sheets("Master SPED Sheet").Range("c4") = Mid$(VarSped, 2) ' print 'VarSped' only if user selected something (i.e. 'VarSped' is not a not string). Mid$() function is used to skip the first character which is a colon
End Sub
养成将Option Explicit
放在每个模块的topo中并明确声明所有变量的习惯:这样既可以节省大量的调试时间,又可以让你对代码有更多的控制权
另一答案
试试这个,看看如何引用循环中的当前项:
Private Sub SpedAccomAddBtn_Click()
Dim VarSped As String
Dim x As Integer
'variable to count multiple selections'
VarSped = " "
'loop to keep track of indexes of selected items'
For x = 0 To Me.SpedListBx.ListCount - 1 'count through list
If Me.SpedListBx.Selected(x) Then
If VarSped = " " Then 'if blank then record first item'
VarSped = Me.SpedListBx.List(x) 'first selected item. +1 because excel is a 0 based index'
Else 'if not the first selection add a , between selections'
VarSped = VarSped & "," & Me.SpedListBx.List(x)
End If
End If
Next x
ThisWorkbook.Sheets("Master SPED Sheet").Range("c4") = VarSped 'print to cell'
End Sub
以上是关于使用listbox multiselect从列表返回多个索引时出错的主要内容,如果未能解决你的问题,请参考以下文章
Kendo UI MVC 从 MultiSelect 小部件将 Grid 绑定到 DataSource