[英]VBA Copy Last 3 Cells of a Column
有沒有辦法可以復制整列的最后 3 個單元格? 在這種情況下,B 列? 謝謝!
Sub LastThree()
Worksheets("DATA").Activate
With Sheets("DATA")
' Adds titles to forecast columns
.Range("I1").Value = "Production Forecast"
.Range("J1").Value = "Demand Forecast"
.Range("K1").Value = "Inventory Forecast"
End With
With Sheets("DATA")
Worksheets("DATA").Activate
.Range("B:B" - 3).Copy
End With
End Sub
由於您使用的是塊With
您不需要使用.Activate
。
首先計算最后一行,然后在取第一個單元格時減去 3:
Option Explicit
Sub LastThree()
With Sheets("DATA")
' Adds titles to forecast columns
.Range("I1") = "Production Forecast"
.Range("J1") = "Demand Forecast"
.Range("K1") = "Inventory Forecast"
Dim LastRow As Long: LastRow = .Cells(.Rows.Count, 2).End(xlUp).Row
.Range(.Cells(LastRow - 2, 2), .Cells(LastRow, 2)).Copy
End With
End Sub
你可以使用:
Option Explicit
Sub LastThree()
Dim LastRow As Long
Dim arrHeaders As Variant
arrHeaders = Split("Production Forecast,Demand Forecast,Inventory Forecast", ",")
With ThisWorkbook.Worksheets("DATA")
LastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
' Adds titles to forecast columns
.Range("I1:K1").Value = Application.WorksheetFunction.Transpose(arrHeaders)
.Range("B" & LastRow - 2 & ":B" & LastRow).Copy
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.