Forum Discussion
Search a column for 2 rows with keywords and hide what's in between them
BriceChapman No need to loop here... just use the Match function to return the row number where "Non - Agented" and "Amendments" are found, then set the Hidden property for the range of Rows to True.
If your daily table always contains sections for "Agented", "Non - Agented" and "Amendments" (in that order), the following code should work:
Sub HideNonAgentedRows()
Dim ws As Worksheet, rg As Range, i As Long, j As Long
Set ws = ThisWorkbook.ActiveSheet
Set rg = ws.Columns(1)
i = WorksheetFunction.Match("Non - Agented", rg, 0)
j = WorksheetFunction.Match("Amendments", rg, 0) - 1
ws.Rows(i & ":" & j).Hidden = True
End Sub
However, it's important to note that the WorksheetFunction.Match method will throw a run-time error if either "Non - Agented" or "Amendments" is not found within the range. If this is a possibility from one day to the next, consider using the Application.Match method instead, which will return an error value if no match is found and can be handled as follows:
Sub HideNonAgentedRows()
Dim ws As Worksheet, lastRow As Long, rg As Range, i As Variant
Set ws = ThisWorkbook.ActiveSheet
lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
Set rg = ws.Range("A1:A" & lastRow)
i = Application.Match("Non - Agented", rg, 0)
If IsError(i) Then Exit Sub
Dim j As Variant
j = Application.Match("Amendments", rg, 0)
If IsError(j) Then
j = lastRow
Else
j = j - 1
End If
ws.Rows(i & ":" & j).Hidden = True
End Sub
Note: the key to making this method work is to declare the i and j variables as type Variant instead of Long, so they can accept either numeric or error values.