Forum Discussion

paul.a.t.krueger's avatar
paul.a.t.krueger
Copper Contributor
Mar 28, 2018
Solved

HELP PLEASE with Macro: delete row if value in row D is below "x" or above "y"

The title says it all, I've been trying for two days now, both using the record function/try to write it myself (didn't work at all) or alter code of others who had written macros with similar tasks ...
  • Jamil's avatar
    Mar 28, 2018

    The most efficient way I know to delete rows using VBA is to use auto-filter feature

     

    You can place this code into a module and try to change the sheet names range and variables x , y to the one you have. 

     

    I wrote this code for the example I have attached. 

     

    you can see that it runs the code on Sheet1 and the range is set after the 25th row, it will ignore the previous rows up to 25th row. ws.Range("A25:O" & lastRow)  also you can change your column from O to whatever your column is

     

    you can assign values to x and y in the code.

     

    if you download the workbook and you run the code in it. you will see what it will do to the data.

     

    Please remember when running any macro, run it on a copy of workbook meaning (you must have a backup copy) because you cannot undo a macro action,  just in case if you click on save by accident.

     

     

     

    Sub Test()
    
    Dim x As Double, y As Double
          x = 7
          y = 4
        Dim ws As Worksheet
        Dim rng As Range
        Dim lastRow As Long
    
        Set ws = ActiveWorkbook.Sheets("Sheet1")
    
        lastRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
    
        Set rng = ws.Range("A25:O" & lastRow)
        With rng
        .AutoFilter Field:=4, Criteria1:="<" & x, Operator:=xlAnd, Criteria2:=">" & y
          .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End With
    
        ws.AutoFilterMode = False
    End Sub
    

     

Resources