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

时间:2014-05-29 00:39:49

标签: excel vba excel-vba

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

我正在尝试这样的事情。列表框的我的列是为每行数据分配的唯一ID。如果选择了这个唯一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

enter image description here

1 个答案:

答案 0 :(得分:1)

<强> EDIT1:
你说Listbox1填充正确。
另外,你说你的身份证是独一无二的。

所以试试这个:

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

未经测试,所以我留给你。