Why I cannot execute a code in an autofiltered dat

2019-09-16 16:52发布

I'm new to VBA. I can populate data into a listbox, perform a delete function on the data list. It works well, but once I autofiltered that data, my delete function cannot work anymore on the filtered data.

I'm trying something like this. My column of the listbox is unique ID assign to each row of data. If this unique ID is selected, it should get its corresponding ("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

enter image description here

1条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-16 17:44

Edit1:
You said Listbox1 is populated correctly.
Also, you said your ID's are unique.

So try this:

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

Not tested so I leave it to you.

查看更多
登录 后发表回答