Link to home
Create AccountLog in
Avatar of sidwelle
sidwelleFlag for United States of America

asked on

I want to copy a WorkSheet w/VBA and specify the name

I want to copy a workSheet w/VBA.


I can use the following:

Sheets("Sheet1").copy Before:=Sheets(1)
ActiveSheet.Name = "Sheet1.bak"

Open in new window

But this method relies on the copied sheet always becoming the 'ActiveSheet'.

This seems like it could be prone to renaming the wrong sheet ?!


Is there no way to supply and/or force a name into copy command ?


Thanks



Avatar of David H.H.Lee
David H.H.Lee
Flag of Malaysia image

Is there no way to supply and/or force a name into copy command ?

Try this:

Sub CopyAndRenameWorksheet()
    Dim ws As Worksheet
    Dim newName As String
    Dim i As Integer

    ' Define the name you want to assign to the copied worksheet
    newName = InputBox("Enter the new worksheet name:", "Rename Worksheet")

    ' Check if a worksheet with the new name already exists
    For i = 1 To Sheets.Count
        If Sheets(i).Name = newName Then
            ' If it exists, prompt the user for a unique name
            Do
                newName = InputBox("Worksheet name already exists. Enter a unique name:", "Rename Worksheet")
            Loop Until Not WorksheetExists(newName)
            Exit For
        End If
    Next i

    ' Copy the worksheet
    Sheets("Sheet1").Copy Before:=Sheets(1)

    ' Rename the copied worksheet
    Set ws = ActiveSheet
    ws.Name = newName
End Sub

Function WorksheetExists(name As String) As Boolean
    On Error Resume Next
    WorksheetExists = Not Worksheets(name) Is Nothing
    On Error GoTo 0
End Function

Open in new window


Is there no way to supply and/or force a name into copy command ?

No there isn't. What you have is correct. The copied sheet will be activated (unfortunately the Copy method doesn't return a reference to the worksheet). You could alternatively add a new worksheet (which does return a reference), rename it, then copy the contents of the source sheet.

ASKER CERTIFIED SOLUTION
Avatar of sidwelle
sidwelle
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer

Seems like overcomplicating life for a problem you don't actually have. Also, sheet names can include commas so using a comma delimited list of sheet names is still prone to error.

Avatar of sidwelle

ASKER

Its a problem that I have and needed a solution.

Thanks for the heads up on the commas.

So you are saying you have actually encountered the wrong sheet being renamed, rather than your original statement that "This seems like it could be prone to renaming the wrong sheet "?

During my testing: Yes.

Curious. I have never seen it happen. Anyway, given that you know where you are copying it to, you could simply refer to it by position.