简体   繁体   中英

Excel VBA: code to copy cells from sheet to new one

I have the below codes to create sheets and rename it from specific list in the master sheet I need a help to add a code to copy some cells from another sheet ( pay slip ) to be pest in each of these new sheets

Sub CreateSheetsFromAList()
    Dim MyCell As Range, MyRange As Range
    Set MyRange = Sheets("MASTER").Range("E9:E27")
    Set MyRange = Range(MyRange, MyRange.End(xlDown))

    For Each MyCell In MyRange
        Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
        Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet

    Next MyCell
End Sub

Which Cells from "Pay Slip" should be copied? For example, I will assume that you want to copy cell (1,1) & cells(2,1) from "Pay Slip" to be copied to new cell.

Modify your code as explained below.

For Each MyCell In MyRange
    Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
    Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet

    ''''Include the Copy steps from PaySlip sheet below this
    Sheets(Sheets.Count).cells(1,1) = Sheets("Pay Slip").cells(1,1)
    Sheets(Sheets.Count).cells(2,1) = Sheets("Pay Slip").cells(2,1)

Next MyCell

You could use .Copy & .PasteSpecial method of Range-object.. Here a simple example -

Sub copySomeRange(r As Range, target As Range)
r.Copy
target.PasteSpecial Paste:=xlPasteAll
End Sub

Sub callMeExample()
Call copySomeRange(Range("A1:A5"), Range("B1"))
End Sub

The first Sub() does the copying so U can use that part of the code as is. Just add your logic to what to copy.

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