Delete Hidden/Invisible Rows after Autofilter Excel VBA

后端 未结 2 1667
借酒劲吻你
借酒劲吻你 2020-12-01 18:36

I guess this is pretty straight forward, but for some reason it just does not seem to work for me :(

I have the below code which auto-filters the data based on the c

相关标签:
2条回答
  • 2020-12-01 19:07

    I used Dmitry Pavliv's solution for my filtered table and it worked (thanks!) but would intermittently give error: "delete method of range class failed" error.

    Error seemed to occur when only one hidden row was to be deleted. It may or may not be of significance that the lone hidden row was right under the table header.

    Stepping through the code, rng pointed to correct cell, and showed just the single cell. It was probably an issue with using a Table instead of named range, though other hidden rows deleted fine in same table format.

    Macro has been working fine after I modified the last portion of the code from this:

    If Not rng Is Nothing Then rng.EntireRow.Delete
    

    To this:

    If rng.Rows.Count = 1 Then
       ws.Rows(rng.Row & ":" & rng.Row).Delete
    ElseIf rng Is Nothing Then
       rng.EntireRow.Delete
    End If
    

    For some reason, deleting that single row in this format works. I'm not quite sure why. The rng object is pointing to the correct cell and I'm using it to get the row number, so not sure why it's not working in rng.entirerow.delete statement. Oh well. Sharing as came across many posts with same error unresolved.

    0 讨论(0)
  • 2020-12-01 19:31

    So I was kind of looking to get rid of Unfiltered Data rather than trying to reverse all the criteria and delete the visible cells

    I would use this one:

    Sub RemoveHiddenRows()
        Dim oRow As Range, rng As Range
        Dim myRows As Range
        With Sheets("Sheet3")
            Set myRows = Intersect(.Range("A:A").EntireRow, .UsedRange)
            If myRows Is Nothing Then Exit Sub
        End With
    
        For Each oRow In myRows.Columns(1).Cells
            If oRow.EntireRow.Hidden Then
                If rng Is Nothing Then
                    Set rng = oRow
                Else
                    Set rng = Union(rng, oRow)
                End If
            End If
        Next
    
        If Not rng Is Nothing Then rng.EntireRow.Delete
    End Sub
    
    0 讨论(0)
提交回复
热议问题