Handling Errors when using VBA to copy a sheet

brianfosterblack

Active Member
Joined
Nov 1, 2011
Messages
251
I am using this code to copy a worksheet and rename the copied sheet
VBA Code:
Sub CopySheet()
Dim ShName As String

        With ActiveSheet
        ShName = .Name & "Copy"
        .Copy After:=Sheets(Worksheets.Count)
        End With
    
    Sheets(Worksheets.Count).Name = ShName
    ActiveSheet.Name = InputBox("Enter the New Sheet name" & vbCr & "making sure it is only one word")
End Sub
This works perfectly but I run into a problem if I name the sheet with a name that already exists
I then get this message "Run Time error 1004 That name is already taken, try a different 1"
Even though I end the sub, a worksheet has been copied with the name of the sheet I copied with the word copy added to the name
I have no idea how to handle errors in VBA. I have tried to read up on this but it is a little over my head.
Can someone please help with the code I need.
 

Excel Facts

Format cells as date
Select range and press Ctrl+Shift+3 to format cells as date. (Shift 3 is the # sign which sort of looks like a small calendar).
How about
VBA Code:
Sub brianfosterblack()
   Dim ShName As Variant
   
   ShName = InputBox("Enter the New Sheet name" & vbCr & "making sure it is only one word")
   If ShName = "" Then Exit Sub
   If Evaluate("isref('" & ShName & "'!A1)") Then
      MsgBox ShName & " is already taken"
      Exit Sub
   End If
   ActiveSheet.Copy , Sheets(Sheets.Count)
   ActiveSheet.Name = ShName
End Sub
 
Upvote 0
Solution
You're welcome & thanks for the feedback.
 
Upvote 0

Forum statistics

Threads
1,214,585
Messages
6,120,399
Members
448,957
Latest member
Hat4Life

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top