Mike
Mike

Reputation: 269

Deleteing rows without a loop meeting certain criteria

I am working on writing a macro that deletes all rows that are less than .75 from a value I found using a formula. In another thread, on here, I found a loop that works, but this takes a lot of time to run... so I am trying to find a way without a loop. So far, I have the code as seen below, but i get a "run-time error 1004, method 'range of object worksheet' failed" on the line

ws.Range(Left(rowsToDelete, Len(rowsToDelete) - 1)).Select

Anybody have any ideas on a correction? All help is appreciated

Private Sub CommandButton6_Click()
Application.ScreenUpdating = False

Dim ws As Worksheet
Dim i&, lr&, rowsToDelete$, lookFor$, lookFor2$

'*!!!* set the condition for row deletion
lookFor = "#VALUE!"
lookFor2 = "0.75"

Set ws = ThisWorkbook.Sheets("Entry")
lr = ws.Range("H" & Rows.Count).End(xlUp).row

ReDim arr(0)

For i = 1 To lr
 If StrComp(CStr(ws.Range("H" & i).Text), lookFor, vbTextCompare) = 0 Or _
    CDbl(ws.Range("H" & i).Value) < CDbl(lookFor2) Then
    ReDim Preserve arr(UBound(arr) + 1)
    arr(UBound(arr) - 1) = i
 End If
Next i

If UBound(arr) > 0 Then
    ReDim Preserve arr(UBound(arr) - 1)
    For i = LBound(arr) To UBound(arr)
        rowsToDelete = rowsToDelete & arr(i) & ":" & arr(i) & ","
    Next i

    ws.Range(Left(rowsToDelete, Len(rowsToDelete) - 1)).Select
    Selection.Delete Shift:=xlUp

    lr = ws.Range("A" & Rows.Count).End(xlUp).row
    ws.Range(lr & ":" & lr).Select
Else
    Application.ScreenUpdating = True
    MsgBox "No more rows contain: " & lookFor & "or" & lookFor2 & ", therefore exiting"
    Exit Sub
End If

If Not Application.ScreenUpdating Then Application.ScreenUpdating = True
Set ws = Nothing
End Sub

Upvotes: 1

Views: 309

Answers (1)

sous2817
sous2817

Reputation: 3960

Here is one way:

Sub Macro1()

With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
    .EnableEvents = False
End With

    Dim r As Range

    Set r = Sheet1.UsedRange

    r.AutoFilter Field:=8, Criteria1:="<.75", _
        Operator:=xlAnd
    r.Offset(1).SpecialCells(xlCellTypeVisible).EntireRow.Delete
    r.AutoFilter

With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
    .EnableEvents = True
End With

End Sub

This assumes that column H (or 8 in the code above) holds the value you want to filter for. You'll have to adjust to fit your sheet.

Upvotes: 2

Related Questions