我有一个基于工作表范围的列表框。我在我的Userform中添加了一个按钮,只要单击它就会删除列表框中的所选项目。每当有一个已删除的项目时,我的工作表范围内的删除的项目也应该被删除。 以下是删除列表框中项目的代码:
Private Sub btnRemove_Click()
Dim i As Integer
For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
ListBox1.RemoveItem (i)
End If
Next i
End Sub
如何删除工作表范围内的已删除项目?谢谢! :)
答案 0 :(得分:3)
由于您使用的是.RemoveItem()
方法,因此您必须通过List
属性设置列表框范围,而不是RowSource
一个
然后您可以在userform代码窗格中使用此代码:
Option Explicit
Dim listRng As Range '<-- declare a Userform scoped variable of 'Range' type to track the range whose content you fill your ListBox1 with (for instance, in Userform_Initialize())
Private Sub btnRemove_Click()
Dim i As Long
Dim rowsList As String
For i = ListBox1.ListCount - 1 To 0 Step -1
If ListBox1.Selected(i) Then
ListBox1.RemoveItem i
Else
rowsList = rowsList & i + 1 & " " '<-- update the rows to be confirmed
End If
Next i
If rowsList <> "" Then UpdateListRange Left(rowsList, Len(rowsList) - 1)
End Sub
Sub UpdateListRange (rowsList As String)
Dim addr As String
Dim iRow As Variant
Dim rowsListArr As Variant
rowsListArr = Split(rowsList)
For iRow = UBound(rowsListArr) To LBound(rowsListArr) Step -1
addr = addr & listRng(rowsListArr(iRow)).address(False, False) & ","
Next iRow
If addr <> "" Then addr = Left(addr, Len(addr) - 1)
Set listRng = listRng.Parent.Range(addr)
End Sub
Private Sub UserForm_Initialize()
With Worksheets("List").Range("C32:C41") '<-- change "List" to your actual worksheet name with the range whose content you fill ListBox1 list with
Me.ListBox1.List = Application.Transpose(.Cells) '<-- fill ListBox1 list
Set listRng = .Cells '<-- set the userform scoped range variable to track the "listbox filling" range
End With
End Sub