excelvba

VBA if cells between number values then delete row


Have a large data set. there are formulas in cells AX:BA

Below is part of the code:

    'Formats cells in column
    Range("AX:BA").NumberFormat = "$#,##0.00"

    'sorts column BA descending
    Range("A1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Sort key1:=Range("Ba1", Range("ba1").End(xlDown)), _
    Order1:=xlDescending, Header:=xlYes

    'deletes any row in AX that is #N/A
    lr = Cells(Rows.Count, "AX").End(xlUp).Row
    For i = lr To 2 Step -1
    If Cells(i, "AX").Text = "#N/A" Then Rows(i).EntireRow.Delete
    Next i

What I'd like to do is replicate the row deletion, but rather than looking for #N/A, it deletes a row where BA is between -$0.01 and $0.01. Alternatively it could delete where absolute value is less than or equal to 1. I need to replace Text = "#N/A" below:

  lr = Cells(Rows.Count, "BA").End(xlUp).Row
    For i = lr To 2 Step -1
    If Cells(i, "BA").Text = "#N/A" Then Rows(i).EntireRow.Delete
    Next i

Not even sure where to start, since I've essentially googled how to do 95% of the current code


Solution

  • To modify your VBA code to delete rows where the value in column BA is between -$0.01 and $0.01 (or equivalently, where the absolute value is less than or equal to 0.01), you need to replace the condition Cells(i, "AX").Text = "#N/A" with a check for the absolute value of the cell in column BA. Since column BA is formatted as currency ($#,##0.00), you can use the ABS function to evaluate the absolute value of the cell’s numeric value. Here’s the updated code snippet to replace the row deletion logic:

    'Formats cells in column
    Range("AX:BA").NumberFormat = "$#,##0.00"
    
    'sorts column BA descending
    Range("A1").Select
    Range(Selection, Selection.End(xlDown)).Select
    Range(Selection, Selection.End(xlToRight)).Select
    Selection.Sort key1:=Range("BA1", Range("BA1").End(xlDown)), _
        Order1:=xlDescending, Header:=xlYes
    
    'deletes any row in AX that is #N/A
    lr = Cells(Rows.Count, "AX").End(xlUp).Row
    For i = lr To 2 Step -1
        If Cells(i, "AX").Text = "#N/A" Then Rows(i).EntireRow.Delete
    Next i
    
    'deletes any row in BA where absolute value is <= 0.01
    lr = Cells(Rows.Count, "BA").End(xlUp).Row
    For i = lr To 2 Step -1
        If IsNumeric(Cells(i, "BA").Value) And Abs(Cells(i, "BA").Value) <= 0.01 Then
            Rows(i).EntireRow.Delete
        End If
    Next i