Return a range from A1 to the true last used cell

后端 未结 4 737
名媛妹妹
名媛妹妹 2020-11-27 05:48

I\'d like to select all the rows and columns in a spreadsheet. The macro needs to be dynamic, as the number of columns and rows tend to vary each time the macro would be cal

4条回答
  •  無奈伤痛
    2020-11-27 06:04

    I figured out how to modify the code to select a range beginning at a specified cell, and ending at the last cell. On line 8, change the a1 to the cell you wish to start on. In my case, I chose j28.

     Set rng3 = Range([j28], Cells(rng1.Row, rng2.Column))
    

    full code:

        Sub GetRange()
            Dim rng1 As Range
            Dim rng2 As Range
            Dim rng3 As Range
            Set rng1 = Cells.Find("*", [a1], , , xlByRows, xlPrevious)
            Set rng2 = Cells.Find("*", [a1], , , xlByColumns, xlPrevious)
            If Not rng1 Is Nothing Then
                Set rng3 = Range([j28], Cells(rng1.Row, rng2.Column))
                MsgBox "Range is " & rng3.Address(0, 0)
                'if you need to actual select the range (which is rare in VBA)
                Application.Goto rng3
            Else
                MsgBox "sheet is blank", vbCritical
            End If
        End Sub
    

提交回复
热议问题