Auto delete duplicated sheets?


Posted by Garbo on March 21, 2001 9:22 PM

I have a vacation log that uses a master sheet to
create sheets for each employee added to the log. The
user is prompted to enter a name and hire date as each
entry is created. If the user duplicates an employee
name exactly, Excel returns a runtime error and names
the sheet 'sheet4', or something similar, as two sheets
cannot have the same name. I need to create an
automatic delete macro, that is transparent to the user
to delete the second entry, if it duplicates a previous
entry. Can anyone suggest a macro to do this?

Thanks for any suggestions...

Posted by Dax on March 22, 2001 4:20 AM


I think an easy way of doing this is to create a function which returns TRUE if a sheet that you are trying to create already exists. If the sheet doesn't exist then the function returns FALSE :-

Function SheetExists(shtName As String) As Boolean
Dim Sht As Worksheet

For Each Sht In ThisWorkbook.Worksheets
If UCase(Sht.Name) = UCase(shtName) Then 'sheet exists
SheetExists = True
Exit For
End If
Next

End Function

Then you could use this function like so :-

Sub AddEmployee()
Dim EmployeeName As String

EmployeeName = InputBox("Please enter your name", "New Employee")

If SheetExists(EmployeeName) Then
Sheets(EmployeeName).Activate
Else
Sheets.Add
ActiveSheet.Name = EmployeeName
End If
End Sub


The new sheet is only added if the employee doesn't already have a sheet. If they do then that sheet is activated.

Regards,
Dax.

Posted by Ivan Moala on March 22, 2001 5:04 AM

you could try this;

Sub Namesheet()
Dim EmployeeName As String

again:
EmployeeName = InputBox("Please enter your name", "New Employee")
If EmployeeName = "" Then goto Ex

Sheets.Add
On Error Resume Next
ActiveSheet.Name = EmployeeName
If Err <> 0 Then
Application.DisplayAlerts = False
ActiveSheet.Delete
GoTo again
End If
On Error GoTo 0
Ex:
Application.DisplayAlerts= True
End Sub

Ivan



Posted by Garbo on March 25, 2001 10:05 PM

Thanks, Dax and Ivan..

I am sorry it took me so long to respond to your
suggestions, but I have been out of town for four
days.

Anyway, both suggestions worked very well and solved
my dilemma. I am happily moving forward, and very
much appreciate the help!


G.