2014-12-08 43 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

在這樣的情況下的另一種選擇是通過以相反的順序進行迭代。從列表底部開始,您不必擔心調整索引,因爲進一步的項目不會因刪除其下方的項目而受到影響。