Search code examples
excelmultiple-columnsworksheet-functionworksheetvba

Excel VBA: How to read Column data and delete Worksheet based on criteria


I have done an extensive amount of research on this topic but no luck so far. I have moderate experience with programming.

That said my issue is in regards to reading data from a column and deleting the worksheet if certain text is read 47 times.

In Column "L" text ("n/m") is repeated 47x times. Text always begins in row 14 and always goes on until row 70. Within that range there are spaces and "--------"

If that column has 47 "n/m" then the worksheet can be deleted and it has to be applied/repeated for the whole workbook which contained around 40 to 100 worksheets.

My code:

First try didn't work

Sub DeletingBlankPages()
Dim Ws As Worksheet
Dim nm As Range

Set nm = Ws.Range(Columns("12"))
Application.ScreenUpdating = False
For Each Ws In ActiveWorkbook.Worksheets
nm.Select

If nm Is "n/m" Then
    Application.DisplayAlerts = False
Ws.Delete
Application.DisplayAlerts = True
End If
Next Ws
End Sub

Second try still didnt work

Sub DeleteRowBasedOnCriteria()
Dim Ws As Worksheet
For Each Ws In ActiveWorkbook.Worksheets
  Application.DisplayAlerts = False

If Range(Columns("12")).Value < 47 > "n/m" _
Then _
    Ws.Delete
    Application.DisplayAlerts = True

End If

Next Ws
End Sub

If any of you with experience know how to solve this please respond. Thank you


Solution

  • If I understand correctly, try this

    Sub DeleteRowBasedOnCriteria()
    
    Dim i As Long
    
    For i = Sheets.Count To 1 Step -1
        If WorksheetFunction.CountIf(Sheets(i).Range("L14:L70"), "n/m") >= 47 Then
            If Sheets.Count > 1 Then
                Application.DisplayAlerts = False
                Sheets(i).Delete
                Application.DisplayAlerts = True
            Else
                MsgBox "Only 1 sheet left"
                Exit Sub
            End If
        End If
    Next i
    
    End Sub