2014-12-08 3 views
1

그래서 userform이 있습니다 : "lstentries"라는 목록 상자 "삭제"라는 라디오 버튼. 또한 "시작"은 행 테이블의 왼쪽 위 모서리에있는 셀의 이름입니다.목록 상자에서 여러 선택 항목을 삭제하는 방법?

이미 코드를 설정하여 목록 상자에서 여러 항목을 선택할 수 있습니다. 그러나 여러 항목을 선택하면 첫 번째 행만 삭제됩니다. 그래서 내가 선택한 루프를 삭제하지 계속 while 루프를 만들려고했는데, 그 중 하나가 작동하지 않습니다. "런타임 오류 '1004'가 발생합니다 - 'Object'_Global '의'Range '메서드가 실패했습니다."

누군가 나를 도울 수 있기를 바랍니다. 다음은 행을 삭제하는 코드 스 니펫입니다. 미리 감사드립니다.

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

또 다른 옵션은 역순으로 반복하는 것입니다. 목록의 맨 아래에서 시작하는 경우 색인을 조정하는 것에 대해 걱정할 필요가 없습니다. 그 이상의 항목은 그 아래에있는 항목을 제거하여 영향을받지 않기 때문입니다.

관련 문제