Can someone debug this code for me. I can't figure out why it isn't working.
Option Explicit
Sub CreateReplaceWorksheet()
Dim oSheet As Worksheet, vBtn As Variant
On Error GoTo errHandler
'creating the new excel worksheet
Set oSheet = Worksheets.Add
With oSheet
.Name = Range("SheetName")
.Cells(1.1).Select
.Activate
End With
Exit Sub
errHandler:
'if error due to "duplicate worksheet detected"
If Err.Number = 1004 Then
'display options to user
vBtn = MsgBox("Worksheet already exists" & Chr$(13) & Chr$(13) & _
"Click OK to delete the OLD worksheet, and create a new one." & Chr$(13) & Chr$(13) & _
"Click CANCEL to go to the old worksheet.", _
vbOKCancel, "Error Resolution")
If vBtn = vbOK Then
'delete the old worksheet
Application.DisplayAlerts = False
Worksheets(Range("SheetName")).Delete
Application.DisplayAlerts = True
'rename and activate the new worksheet
With oSheet
.Name = Range("SheetName")
.Cells(1.1).Select
.Activate
End With
Else
'cancel the operation, delete the new worksheet
Application.DisplayAlerts = False
oSheet.Delete
Application.DisplayAlerts = True
End If
End If
End Sub
Here is the goal of the code:
Check for a Worksheet with the name found in NamedRange "SheetName".
If Worksheet NOT found...then Create Worksheet named "SheetName".
If Worksheet FOUND...then MsgBox outlining User Options.
Option 1: DELETE old Worksheet and Create NEW Worksheet named "SheetName".
Option 2: GO TO old worksheet.
Option 2 works perfectly.
Option 1 results in Run-time error '13': Type mismatch
The error occurs on the following line:
'delete the old worksheet
Application.DisplayAlerts = False
Worksheets(Range("SheetName")).Delete
Application.DisplayAlerts = True
I read online that sometimes...a copy/paste of VBA will cause this error.
So I deleted the line of code that was flagged...and typed it manually.
Obviously...that didn't work, or you wouldn't be reading this.
(It DID work, however, on another section of the code that was producing the same error).
Have I coded something wrong?? Or...is there some other problem??
Attached...is a sample Workbook...for examination.
Bookmarks