Поиграл и придумал код ниже. Показывает не использование Select
и избавление от On Error Resume Next
.
Option Explicit 'VERY IMPORTANT!!!!!!!!
'Place at top of every new module by selecting Tools ~ Options and ticking
'Require Variable Declaration.
Sub CreateSheet()
Dim xName As String
Dim xSht As Object
Dim IllegalCharacters As Variant
Dim iChr As Variant
Dim shtNew As Worksheet
Dim shtLCreator As Worksheet
On Error GoTo Err_Handle
IllegalCharacters = Array("/", "\", "[", "]", "*", "?", ":")
xName = InputBox("Please enter a name for this new sheet.")
'Remove any illegal characters from sheet name.
For Each iChr In IllegalCharacters
xName = Replace(xName, iChr, "")
Next iChr
If Len(xName) > 0 Then
If WorkSheetExists(xName) Then
MsgBox "Cannot create sheet '" & xName & "' as it already exists.", vbOKOnly + vbCritical
Else
Set shtNew = ThisWorkbook.Worksheets.Add
shtNew.Name = xName
Set shtLCreator = ThisWorkbook.Worksheets("New Ledger Creator")
shtLCreator.Cells(Rows.Count, 2).End(xlUp).Offset(1) = xName
With ThisWorkbook.Worksheets("123")
.Range("A1") = "Paid"
.Range("A2:J2") = Array("Paid", "Date", "For", "Through", "Amount", _
"Remarks", "Date", "For", "Through", "Amount", "Remarks")
End With
End If
End If
FAST_EXIT:
Exit Sub
Err_Handle:
Select Case Err.Number
Case 11 'Division by 0
MsgBox "Somehow a division by 0 happened." & vbCr & _
"Well done, you did the impossible - there's no calculations in this code.", vbOKOnly
'Resume Next 'Error was dealt with, so continue on line following error.
'Resume 'Error was dealt with so continue on same line that caused error.
Resume FAST_EXIT 'Error was dealt with, resume at Fast_Exit label.
Case Else
MsgBox Err.Description, vbOKOnly + vbCritical, Err.Number
End Select
End Sub
'Checks if a worksheet exists - returns TRUE/FALSE
Public Function WorkSheetExists(SheetName As String, Optional WrkBk As Workbook) As Boolean
Dim wrkSht As Worksheet
If WrkBk Is Nothing Then
Set WrkBk = ThisWorkbook
End If
On Error Resume Next
Set wrkSht = WrkBk.Worksheets(SheetName)
WorkSheetExists = (Err.Number = 0)
Set wrkSht = Nothing
On Error GoTo 0
End Function