简体   繁体   中英

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

As an Excel VBA newb, I'm not finding a solution to this.

I have a sheet of a 1,000 plus rows. I'm trying to create a macro that will 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).

Here is the basic idea I'm aiming at.

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

Thank you.

Help Appreciated.

Guy

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM