为什么我不能在vba中的自动过滤数据列表中执行代码?

我是VBA新手。 我可以将数据填充到列表框中,在数据列表上执行删除function。 它工作得很好,但是一旦我自动过滤了这些数据,我的删除function就不能再对已过滤的数据进行操作了。

我正在尝试这样的事情。 列表框的列是唯一的ID分配给每行数据。 如果select了这个唯一的ID,它应该得到相应的(“H2”)。offset =“Discarded”

Private Sub DeleteCartonButton_Click() Dim myindex, index Dim i As Long With ListBox1 For i = 0 To .ListCount - 1 If .Selected(i) Then If IsEmpty(myindex) Then myindex = Array(i) ElseIf IsArray(myindex) Then ReDim Preserve myindex(UBound(myindex) + 1) myindex(UBound(myindex)) = i End If End If Next End With index = Me.ListBox1.List(Me.ListBox1.ListIndex, 0) If IsEmpty(myindex) Then Exit Sub '~~> if nothing is selected '~~> update the sheet With Sheet1 For Each index In myindex .Range("H2").Offset(index, 0).Value = "Discarded" Next End With '~~> update the ListBox1 display DoEvents ListBox1.RowSource = rSource.Address(external:=True) End Sub 

在这里输入图像说明

EDIT1:
你说Listbox1正确填充。
另外,你说你的ID是独一无二的。

所以试试这个:

 Dim myid As String, rtarget As Range With Sheet1 For Each index In myindex myid = Listbox1.List(index, 0) Set rtarget = .Range("A:A").Find(myid, [a1]) '~~> Assuming ID's in ColA If Not rtarget Is Nothing Then rtarget.Offset(0,7) = "Discarded" Set rtarget = Nothing Next End With 

没有testing,所以我把它留给你。