2014-12-08 50 views
1

所以我有一个用户表单有一个: 列表框称为“lstentries” 单选按钮称为“删除”。 此外,“开始”是行表格左上角的单元格的名称。如何删除列表框中的多个选择?

我已经设置了代码,以便它可以在列表框中选择多个条目。但是,当我选择多个条目时,它只会删除它所涉及的第一行。所以我试着做一个while循环,所以它一直删除选定的,但这也不起作用。我得到“运行时错误'1004' - 对象的方法'范围''全局'失败”

希望有人能帮助我。这里是删除行的代码片段。提前致谢。

If optDelete.Value = True Then 
     Dim delete As Range 
     Do While True 
      Set delete = Range("start").Offset(lstEntries.ListIndex, 0) 
      delete.EntireRow.delete Shift:=xlUp 
     Loop 
    End If 

回答

0

在列表框中,您可以运行项目列表。由于您允许选择和删除多个项目,因此在删除项目时必须调整索引。

列表框0索引它从0开始,这意味着,不1.

' set the to go through all items in the list 
For listIndexCount = 0 To lstEntries.ListCount 

    ' check to make sure the index count is not greater or equal to the total number of items 
    ' this is needed because the ListCount will change if items are deleted 
    If listIndexCount >= lstEntries.ListCount Then 
     Exit Sub 
    End If 

    ' check to see if the item is selected 
    If lstEntries.Selected(listIndexCount) Then 

     ' remove item 
     lstEntries.RemoveItem (listIndexCount) 

     ' subtract 1 to account for removed item 
     listIndexCount = listIndexCount - 1 
    End If 
Next 
0

在这样的情况下的另一种选择是通过以相反的顺序进行迭代。从列表底部开始,您不必担心调整索引,因为进一步的项目不会因删除其下方的项目而受到影响。

相关问题