简体   繁体   中英

How to use cell value in a macro to copy a range of data to new worksheet

I have been googling for a while but not able to find a solution, hoping someone can help.

I'm trying to copy a range of data from one worksheet (Sheet1) to a new worksheet (Sheet2), the start of the range always remain the same (Column A, Cell 3) but the Row changes depending on input data. I need this a macro so it can be assigned to a button.

Eg: I need to copy all data from A1 to E3 to a new worksheet but the next time the range maybe from A1 to E4 as more data is inputed. The columns will alway remain the same (A & E) but the row will be different each time.

Please help

例

Current code

Sub CopyItOver()

Dim lastRow As Long
Dim CellNum As String

RowLetter = "U"
lastRow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
Worksheets("data").Range("$H$1").Value = lastRow
CellNum = RowLetter & lastRow
Worksheets("data").Range("$H$2").Value = CellNum

Set NewBook = Workbooks.Add
Workbooks("template.xlsm").Worksheets("data").Range("A3:cellnum").Copy
NewBook.Worksheets("Sheet1").Range("A1").PasteSpecial (xlPasteValues) Range("R:R").NumberFormat = "dd-mm-yyyy;@"

End Sub

I'm trying to copy a range of data from one worksheet (Sheet1) to a new worksheet (Sheet2)...

Try this

Sub CopyPaste1()
Sheets("Sheet2").Cells.Clear
LastRowColumnE = Cells(Rows.Count, "E").End(xlUp).Row
Worksheets("Sheet1").Range("A1:E" & LastRowColumnE).Copy Destination:=Worksheets("Sheet2").Range("A1")
End Sub

Alternatively,

Sub CopyPaste2()
Sheets("Sheet2").Cells.Clear
LastRowColumnE = Cells(Rows.Count, 5).End(xlUp).Row
Sheets("Sheet1").Range(Cells(1, 1), Cells(LastRowColumnE, 5)).Copy Destination:=Sheets("Sheet2").Cells(1, 1)
End Sub

Or

Sub CopyPaste3()
Sheets("Sheet1").Columns("A:E").Copy Destination:=Sheets("Sheet2").Columns(1)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM