'How do I hide a range of rows by getting the start and end row values from user input cells?

I have a sheet of 1,000 plus rows.

I'm trying to hide all rows that match the values I input into cells A1 (the starting row in the range), and cell A2 (the end row in the range).

Sub Macro1()
'
' Hide rows when row numbers are between the values in cell A1 and Cell A2.
'
'   Range("A1:A15").Select 'Trying to modify this so that I get values from Cells A1 and A2.
    Rows(Range("A1").Value:Range("A2").Value).Select ' This is my failed attempt.
    Selection.EntireRow.Hidden = True
    Range("A1").Select
End Sub


Solution 1:[1]

Based on my comment, I'm going to assume you want to hide the rows (inclusive) between the two values you specify in A1 and A2.

You'll need to clean it up to make sure the correct sheet is having this applied to it. Right now, it works on the active sheet.

I've also assumed that if you change the numbers, you want to unhide all of the previously hidden rows.

Public Sub HideRows()
    Dim lngRowFrom As Long, lngRowTo As Long, objSheet As Worksheet
    
    Set objSheet = ActiveSheet
    
    With objSheet
        On Error GoTo ErrorCatchNotNumeric

        lngRowFrom = .Range("A1").Value
        lngRowTo = .Range("A2").Value
        
        On Error GoTo 0
        
        If lngRowFrom > .Rows.Count Or lngRowFrom < 1 Then GoTo ErrorCatchNotNumeric
        If lngRowTo > .Rows.Count Or lngRowTo < 1 Then GoTo ErrorCatchNotNumeric
        
        If lngRowFrom > lngRowTo Then
            MsgBox "Your ""From"" row is greater than your ""To"" row.", vbCritical, "Error"
        Else
            .Rows.Hidden = False
            .Rows(lngRowFrom & ":" & lngRowTo).EntireRow.Hidden = True
        End If
    End With
    
    Exit Sub
    
ErrorCatchNotNumeric:
    MsgBox "The values you supplied are not valid!", vbInformation, "Error"
    
End Sub

Adapt it as you see fit.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Skin