简体   繁体   中英

Dynamic Range With A Maximum End Point in Excel VBA

I am using this line to find the end of a dynamic range starting in B9:

Sheets("Summary").Range("B9", Sheets("Summary").Range("B" & Rows.Count).End(xlUp))

The range may anywhere from 2 rows long to 20 rows long but I need to set a limit to the range at 21 rows.

How do I do this?

Thanks

Find the last row and check if it is greater then 21. If it is, then set the last row as 21 . See this. Also it is advisable to work with objects and variables. Code becomes easier to handle :)

Option Explicit

Sub Sample()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim rng As Range
    Dim lRowLimit As Long
    
    Set ws = ThisWorkbook.Sheets("Summary")
    
    '~~> Set the limit here
    lRowLimit = 21
    
    With ws
        lRow = .Range("B" & .Rows.Count).End(xlUp).Row
        
        If lRow > lRowLimit Then lRow = lRowLimit
        
        Set rng = .Range("B9:B" & lRow)
        
        Debug.Print rng.Address
    End With
End Sub

The range may anywhere from 2 rows long

Note : In such a case you want .Range("B9:B" & lRow) to be .Range("B1:B" & lRow) ?

You need to count the rows in the same worksheet as you set the range. Therefore:-

Set Rng = Sheets("Summary").Range("B9", Sheets("Summary").Range("B" & Sheets("Summary").Rows.Count).End(xlUp))

But if you want to limit the end row you should determine a row number, like this.

Dim Rng     As Range
Dim Rl      As Long                 ' last row

With Sheets("Summary")
    Rl = WorksheetFunction.Min(.Range("B" & .Rows.Count).End(xlUp).Row, 21)
    Set Rng = Range(.Range("B9"), .Cells(Rl, "B"))
End With

Also

Sub Test()

    Const MaxRow = 29
    Dim MyRange As Range
    
    With Sheets("Summary")
        Set MyRange = .Range("B9", "B" & IIf(.Range("B" & Rows.Count).End(xlUp).Row > MaxRow, MaxRow, _
        .Range("B" & Rows.Count).End(xlUp).Row))
    End With

End Sub

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