Delete cells in an Excel column when rows = 0

前端 未结 4 1901
有刺的猬
有刺的猬 2020-11-28 16:19

I am trying to delete all cells =0 in a column in my spreadsheet and \"summon\" the values which don\'t to the top of the column.

I am currently using



        
相关标签:
4条回答
  • 2020-11-28 16:40

    Yes, there is:

    Sub DoMAcro()
        Dim lastRow As Integer
    
        lastRow = Cells(1000, 16).End(xlUp).Row
    
        Range(Cells(7, 16), Cells(lastRow, 16)).Replace What:="0", Replacement:="", LookAt:=xlPart, _
            SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
    End Sub
    
    0 讨论(0)
  • 2020-11-28 16:48

    Autofilter solution

    Dim rng1 As Range
    Set rng1 = Range([p7], Cells(Rows.Count, "p").End(xlUp))
    ActiveSheet.AutoFilterMode = False
    With rng1
    .AutoFilter Field:=1, Criteria1:="0"
    .Delete xlUp
    End With
    
    0 讨论(0)
  • 2020-11-28 17:02

    Deleting cells in a loop can really be very slow. What you could do is identify the cells that you want to delete in a loop and then delete them in one go after the loop. Try this.

    Option Explicit
    
    Sub Sample()
        Dim row_index As Long, lRow As Long, i As Long
        Dim ws As Worksheet
        Dim delRange As Range
    
        '~~> Change this to the relevant worksheet
        Set ws = ThisWorkbook.Sheets("Sheet1")
    
        row_index = 7
    
        Application.ScreenUpdating = False
    
        With ws
            lRow = .Range("P" & .Rows.Count).End(xlUp).Row
    
            For i = row_index To lRow
                If .Range("P" & i).Value <> "" And .Range("P" & i).Value = 0 Then
                    If delRange Is Nothing Then
                        Set delRange = .Range("P" & i)
                    Else
                        Set delRange = Union(delRange, .Range("P" & i))
                    End If
                End If
            Next
        End With
    
        If Not delRange Is Nothing Then delRange.Delete shift:=xlUp
        Application.ScreenUpdating = True
    End Sub
    
    0 讨论(0)
  • 2020-11-28 17:04

    To speed things up, you probably also want to turn auto calculation off while you do the update:

    Application.Calculation = xlCalculationManual
    

    Then change it back to automatic when you are done:

    Application.Calculation = xlCalculationAutomatic
    
    0 讨论(0)
提交回复
热议问题