如何删除多个列表框项并在rowsource中更新?

时间:2018-02-21 04:58:19

标签: excel vba excel-vba excel-formula

我有一个使用文本框动态更新的列。我可以使用文本框更新列,并在列表框中更新这些值。

我尝试从列表框中删除多个数据。但它告诉我错误。 我需要从列表框和工作表列中删除数据,并通过删除空格并向上移动来更新列。

我用于向列表框提供数据的数据列是动态的。结束范围不固定。

我得到一个未定义的变量错误,如果我做一些调整,我会得到调试错误或代码错误

我的代码:

Private Sub CommandButton2_Click()
 Dim iItem As Long, iRow As Long

    With Sheet3 'reference Sheet3
        Set r1 = .Range("A2:A" & .Range("A" & .Rows.Count).End(xlUp).Row) ' set current data range
    End With

    With Me.ListBox1 'reference your list box
        iItem = .ListCount - 1 ' start from last listbox item
        Do
            If .Selected(iItem) Then ' if current listbox item selected
                For iRow = r1.Rows.Count To 1 Step -1 'loop through data range rows from bottom to top
                    If r1.Cells(iRow).Value = .List(iItem) Then r1.Cells(iRow).EntireRow.Delete 'if current selected listbox index matches current data range cell value then delete this latter entire row
                Next
                .RemoveItem (iItem) ' remove selected item from the listbox
            End If
            iItem = iItem - 1 'update listbox item to the "next" one (i.e. the one above)
        Loop While iItem >= 0 ' loop till reaching first listbox item
    End With
End Sub

Private Sub ListBox1_Click()

End Sub

Sub UserForm_Initialize()
Range("A2").Select
End Sub

Private Sub CommandButton1_Click()
If TextBox1.Value = "" Then
    MsgBox ("Please Add the component name")

Else

    ActiveCell = TextBox1.Value
    ActiveCell.Offset(1, 0).Select

    ListBox1.RowSource = "Sheet3!A2:A" & Range("A" & Rows.Count).End(xlUp).Row
    Call resetForm


End If
End Sub

Sub resetForm()
TextBox1.Value = ""
TextBox1.SetFocus
End Sub

1 个答案:

答案 0 :(得分:1)

Collections删除项目时(如Range中的ListBox项中的行),您应该从下到上进行操作,避免同时跳过项目并处理不存在的项目< / p>

如下(评论中的解释)

Private Sub CommandButton2_Click()
    Dim r1 As Range
    Dim iItem As Long, iRow As Long

    With Sheet3 'reference Sheet3
        Set r1 = .Range("A2:A" & .Range("A" & .Rows.Count).End(xlUp).Row) ' set current data range
    End With

    With Me.ListBox1 'reference your list box
        iItem = .ListCount - 1 ' start from last listbox item
        Do
            If .Selected(iItem) Then ' if current listbox item selected
                For iRow = r1.Rows.Count To 1 Step -1 'loop through data range rows from bottom to top
                    If r1.Cells(iRow).Value = .List(iItem) Then r1.Cells(iRow).EntireRow.Delete 'if current selected listbox index matches current data range cell value then delete this latter entire row
                Next
                .RemoveItem (iItem) ' remove selected item from the listbox
            End If
            iItem = iItem - 1 'update listbox item to the "next" one (i.e. the one above)
        Loop While iItem >= 0 ' loop till reaching first listbox item
    End With
End Sub