Search code examples
vbaexcelfinance

Loop through sheets and delete those which do not meet a condition


I am using an Excel model to pull stock data off Yahoo Finance. The results for each stock are downloaded into a different worksheet within the Excel workbook. After running the model, the workbook has many sheets, some of which contain unusable data.

I am looking to create VBA code that loops through each worksheet and checks for a condition, namely if cell A66 contains the date 12/31/2014. If this condition is not met, the sheet needs to be deleted.


Solution

  • You can try this Macro.

    Sub checkSheets()
        For i = ActiveWorkbook.Sheets.Count To 1 Step -1
            If ActiveWorkbook.Sheets(i).Cells(66, 1) <> CDate("12/31/2014") Then
                ActiveWorkbook.Sheets(i).Delete
            End If
        Next
    End Sub