Home > Blockchain >  Defining last nine rows of data as range to copy values and transpose paste into another worksheet
Defining last nine rows of data as range to copy values and transpose paste into another worksheet

Time:01-31

What is the VBA code to define a range that is always the last nine rows of data?

I have a data table that is manually updated monthly for 9 subjects. I want to copy specific cell values from the most recent entries and populate a scorecard on another worksheet with those values.

What I can’t figure out how to do is define a dynamic range from the last row up 9.

I can define the last row using

Last = Cells(Rows.Count, “B”).End(xlUp).Row

But how do I define the last 9 rows?

Last = Cells(Rows.Count, “B”).End(xlUp).Row

‘First???

For i=Last To ‘first Step -1

‘If “name” then copy cell values to defined cell in scorecard

CodePudding user response:

Transpose Last Rows

Sub PrintLastRowsAddress()

    Const LAST_ROWS_COUNT As Long = 9
 
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim lrg As Range

    With ws.UsedRange
        Set lrg = .Resize(LAST_ROWS_COUNT).Offset(.Rows.Count - LAST_ROWS_COUNT)
    End With
    
    Debug.Print lrg.Address(0, 0)
    
End Sub

enter image description here

Sub TransposeLastRows()

    Const SRC_NAME As String = "Sheet1"
    Const SRC_LAST_ROWS As Long = 9
    Const DST_NAME As String = "Sheet2"
    Const DST_FIRST_CELL As String = "A1"
 
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim sws As Worksheet: Set sws = wb.Sheets(SRC_NAME)
    Dim srg As Range
    With sws.UsedRange
        Set srg = .Resize(SRC_LAST_ROWS).Offset(.Rows.Count - SRC_LAST_ROWS)
    End With
    
    Dim dws As Worksheet: Set dws = wb.Sheets(DST_NAME)
    Dim dfCell As Range: Set dfCell = dws.Range(DST_FIRST_CELL)
    Dim drg As Range: Set drg = dfCell.Resize(srg.Columns.Count, SRC_LAST_ROWS)
    
    drg.Value = Application.Transpose(srg.Value)
    
    MsgBox "Last " & SRC_LAST_ROWS & " rows transposed.", vbInformation
    
End Sub

CodePudding user response:

Range(Cells(max(1,Last-9),2),Cells(Last,2))

Handles the case of less than 9 rows with data.

Set the columns to whatever width you need the final range to be.

  • Related