[英]Defining last nine rows of data as range to copy values and transpose paste into another worksheet
What is the VBA code to define a range that is always the last nine rows of data? VBA 定义一个始终为最后九行数据的范围的代码是什么?
I have a data.table that is manually updated monthly for 9 subjects.我有一个 data.table,每月手动更新 9 个主题。 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.我不知道该怎么做是从最后一行开始定义一个动态范围 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?但是我如何定义最后 9 行呢?
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 '如果是“名称”,则将单元格值复制到记分卡中定义的单元格
Range(Cells(max(1,Last-9),2),Cells(Last,2))
Handles the case of less than 9 rows with data.处理少于 9 行数据的情况。
Set the columns to whatever width you need the final range to be.将列设置为您需要最终范围的任何宽度。
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
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.