A Worksheet BeforeRightClick: Copy and Rename Template Worksheet
Sheet Module e.g. Sheet1
Option Explicit
Private Sub Worksheet_BeforeRightClick(ByVal Target As Range, Cancel As Boolean)
AddNewEmployeeDetails Target, Cancel
End Sub
Standard Module e.g. Module1
Option Explicit
Sub AddNewEmployeeDetails(ByVal Target As Range, ByRef Cancel As Boolean)
Const PROC_TITLE As String = "Add New Employee Details Sheet"
Const TARGET_RANGE As String = "B6:F11"
Const SRC_SHEET_NAME As String = "Employee Details"
Const AFTER_SHEET_NAME As String = "Job Schedule"
Const DST_SHEET_NAME_PREFIX As String = "Employee Details - "
Dim tws As Worksheet: Set tws = Target.Worksheet
Dim trg As Range: Set trg = Intersect(tws.Range(TARGET_RANGE), Target)
If trg Is Nothing Then Exit Sub
Dim eName As String: eName = CStr(Target.Value) ' for the message boxes
Dim dName As String: dName = DST_SHEET_NAME_PREFIX & eName
Dim wb As Workbook: Set wb = tws.Parent
Dim dsh As Object
On Error Resume Next ' to prevent error if sheet doesn't exist
Set dsh = wb.Sheets(dName)
On Error GoTo 0
If dsh Is Nothing Then ' sheet doesn't exist
Dim sws As Worksheet: Set sws = wb.Sheets(SRC_SHEET_NAME)
Dim aws As Worksheet: Set aws = wb.Sheets(AFTER_SHEET_NAME)
sws.Copy After:=aws
Dim dws As Worksheet: Set dws = aws.Next
Dim ErrNumber As Long, ErrDescription As String
On Error Resume Next ' to prevent error if invalid sheet name
dws.Name = dName
ErrNumber = Err.Number
ErrDescription = Err.Description
On Error GoTo 0
If ErrNumber <> 0 Then ' sheet name is invalid
Application.DisplayAlerts = False ' to delete without confirmation
dws.Delete
Application.DisplayAlerts = True
tws.Select
MsgBox "Run-time error '" & ErrNumber & "':" & vbLf & vbLf _
& ErrDescription & vbLf & vbLf & "Could not rename to """ _
& dName & """.", vbCritical, PROC_TITLE
Else ' sheet name is valid
MsgBox "Employee Details sheet for " & eName & " added.", _
vbInformation, PROC_TITLE
End If
Else ' sheet exists
MsgBox "The Employee Details sheet for " & eName _
& " already exists.", vbCritical, PROC_TITLE
End If
Cancel = True
End Sub