Excel VBA - select a dynamic cell range

前端 未结 4 1613
猫巷女王i
猫巷女王i 2020-12-13 11:08

I want to be able to dynamically select a range of cells (the heading row), where the row is 1 but the columns with be for 1 to last column, where \"A\" is the first Column

4条回答
  •  不知归路
    2020-12-13 11:56

    I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.

    Sub DynamicRange()
    'Best used when first column has value on last row and first row has a value in the last column
    
    Dim sht As Worksheet
    Dim LastRow As Long
    Dim LastColumn As Long
    Dim StartCell As Range
    
    Set sht = Worksheets("Sheet1")
    Set StartCell = Range("A1")
    
    'Find Last Row and Column
      LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
      LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
    
    'Select Range
      sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
    
    End Sub
    

提交回复
热议问题