简体   繁体   中英

Copy and paste into a new sheet that is created in the same VBA code

I can't find the answer to this question anywhere in here or at else on the internet! So please help me:

Objective

1) I wan't to create a new sheet that I name, 2) thereafter I wan't to copy specific cells into this newly created sheet.

Background

I've seen thousands of videos explaining the code to create a new sheet and name it after what I write in a certain cell, so far so good. I've also seen thousands where you copy values into an already existing sheet, nice. But I can't find anyone describing how to create a new sheet, named as Idefine in a specific cell, and then copy values into it; and when I'm changing the name in the specific cell, I want to copy to that the new sheet.

Here's the code I did for the first part (working fine) and the second part (working not so fine):

        sheet_name_to_create = Blad1.Range("e33").Value

        For rep = 1 To (Worksheets.Count)
            If LCase(Sheets(rep).Name) = LCase(sheet_name_to_create) Then
            MsgBox "This sheet already exists!)"
            Exit Sub
            End If

        Next

        ' börja kopieringen


            Sheets.Add After:=ActiveSheet
            Sheets(ActiveSheet.Name).Name = sheet_name_to_create

    'Second part trying to copy and paste
    'Now I want to copy values in "Blad1" to the newly made sheet ("sheet_name_to_create"). I know these codes are wrong, but it's what I got:

     Range("A1:AM73").Select
        Selection.Copy
        Sheets.Add After:=ActiveSheet
        ActiveSheet.Paste
        ActiveWindow.Zoom = 25

' Or

    WorksWorksheets("Blad1").Range ("A1:AF80").Copy Worksheets("sheet_name_to_create").Range ("A1:AF80")

Please help

When you create the new sheet, reference it - like so:

Set sourceSheet = ActiveSheet
Set destSheet = Sheets.Add(After:=sourceSheet)

You can now reference either the source worksheet or destination using sourceSheet and destSheet .

Then you can apply a name to your destSheet :

destSheet.Name = sheet_name_to_create

And then you can copy/paste from source to destination sheet:

sourceSheet.Range("A1:AM73").Copy destSheet

So your code becomes:

sheet_name_to_create = Blad1.Range("e33").Value

For rep = 1 To (Worksheets.Count)
    If LCase(Sheets(rep).Name) = LCase(sheet_name_to_create) Then
        MsgBox "This sheet already exists!)"
        Exit Sub
    End If
Next
Set sourceSheet = ActiveSheet
Set destSheet = Sheets.Add(After:=sourceSheet)

destSheet.Name = sheet_name_to_create
sourceSheet.Range("A1:AM73").Copy destSheet
ActiveWindow.Zoom = 25

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