Excel VBA: If value not found in range, go to

excelvba

I am using the following code to loop through sheets 1-31 filtering each sheet by the value in a cell("E1") in sheets("RunFilter_2") and then copy the filtered range and copy to the next empty row in sheets("RunFilter_2").

The code errors when it doesn't find the value of sheets("RunFilter_2").Range("E1") in column 18 of the active sheet.

So I added a range check, that checks if sheets("RunFilter_2").Range("E1").Value is found in column Range("R:R").

But, how do I move to the Next I If rngFound Is Nothing?

Sub RunFilter2()

Rows("5:5").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp
Range("A1").Select

    Dim wb As Workbook
    Dim ws As Worksheet

    Set wb = ActiveWorkbook
    Set ws = wb.sheets("01")

         Dim WS_Count As Integer
         Dim I As Integer

         WS_Count = ActiveWorkbook.Worksheets.Count - 3

         For I = 1 To WS_Count

Dim LastRow As Long
LastRow = ActiveSheet.UsedRange.Rows.Count

sheets(I).Select

Columns("A:U").Select

Dim rng As Range
Dim rngFound As Range

Set rng = Range("R:R")

Set rngFound = rng.Find(sheets("RunFilter_2").Range("E1").Value)

If rngFound Is Nothing Then

'----------------------------------
' How do I code ... GO TO Next I
'----------------------------------

Else:

Selection.AutoFilter

ActiveSheet.Range("$A$1:$U" & LastRow).AutoFilter Field:=18, Criteria1:=sheets("RunFilter_2").Range("E1").Value

    Range("A1").Offset(1, 0).Select
    Rows(ActiveCell.Row).Select
    Range(Selection, Selection.End(xlDown)).Select
    Selection.Copy

sheets("RunFilter_2").Select

If Range("A4").Value = "" Then

Range("A4").Select

Else

Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select

End If

ActiveSheet.Paste
ws.Select
Application.CutCopyMode = False
Selection.AutoFilter
Range("A1").Select
sheets("RunFilter_2").Select

         Next I

End Sub

Best Answer

You can do it like this:

For I = 1 To WS_Count
    If rngFound Is Nothing Then goto NextIPlace
    your code
NextIPlace:
Next I

But you should reconsider writing like this, it is not a good VBA practice to use GoTo. The whole code should be changed. Check more here. Once your code works, feel free to submit it at https://codereview.stackexchange.com/, they would give you good ideas.

Related Topic