VBA to insert and name sheet but avoid duplicate sheet name

General Ledger

Active Member
Joined
Dec 31, 2007
Messages
460
Dear All,

I have VBA to add a new sheet.

Code:
    ActiveSheet.Copy Before:=Sheets(1)
    ActiveSheet.NAME = "Entry"

However, I get an error if that sheet name already exits.

Run-time error '1004':
Cannot rename a sheet to the same name as another sheet, a referenced object library or a workbook referenced by Visual Basic.

How can I insert a new sheet and name it without creating a duplicate?

Concatenating a sequence number to the end of the sheet name if the desired name already exits is fine. This would create sheets with names: Entry, Entry 1, Entry 2, etc.

Thanks,

GL
 

Excel Facts

When they said...
When they said you are going to "Excel at life", they meant you "will be doing Excel your whole life".
Try like this

Code:
Sub test()
Dim i As Long, s As String, s2 As String
s = "Entry"
s2 = s
ActiveSheet.Copy Before:=Sheets(1)
Do While WorksheetExists(s2)
    i = i + 1
    s2 = s & " " & i
Loop
ActiveSheet.Name = s2
End Sub


Function WorksheetExists(WSName As String) As Boolean
On Error Resume Next
WorksheetExists = Worksheets(WSName).Name = WSName
On Error GoTo 0
End Function
 
Upvote 0

Forum statistics

Threads
1,224,505
Messages
6,179,153
Members
452,891
Latest member
JUSTOUTOFMYREACH

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