使用列表框多选从列表返回多个索引时出错

时间:2019-04-12 22:09:55

标签: excel vba listbox

VBA的新手,有些沮丧。试图为我的同伴们设计一个简化文书工作的表格。

我有一个表单列表 1.苹果
2.橙色
3.葡萄

如果用户要从列表中选择苹果和葡萄,我希望该单元格仅具有索引。因此要在单元格中打印(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不断被覆盖。 (我是编码的新手,必须评论所有内容,以便感觉自己知道自己在做什么)

2 个答案:

答案 0 :(得分:0)

尝试一下,看看如何在循环中引用当前项目:

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

答案 1 :(得分:0)

您的循环迭代器已经是您的商品位置:只需向其添加一个即可管理基于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放在每个模块的最顶层,并显式声明所有变量:这样既可以节省大量调试时间,又可以对代码进行更多控制