1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
Sub Create_NewWS()
Dim Wsh As Worksheet, ActWsh As Worksheet
Dim ActWsN As String, NewWsN As String
Dim CurWsA As Variant
Dim WshInd As Integer
Set ActWsh = ThisWorkbook.Worksheets(1)
ActWsN = ActWsh.Name
WshInd = 0
For Each Wsh In ThisWorkbook.Worksheets
If Wsh.Name = ActWsN Then
WshInd = WshInd + 1
CurWsA = Split(Wsh.Name, "(")
If UBound(CurWsA, 1) > 0 Then
Debug.Print CInt(Left(CurWsA(UBound(CurWsA, 1)), Len(CurWsA(UBound(CurWsA, 1))) - 1))
WshInd = CInt(Left(CurWsA(UBound(CurWsA, 1)), Len(CurWsA(UBound(CurWsA, 1))) - 1)) + 1
End If
ActWsN = ActWsN & "(" & WshInd & ")"
End If
Next Wsh
End Sub
Function Exist_Wsh(Wbk As Workbook, WshName As String, Optional CreateSh As Boolean = False, Optional Prompt_creat As Boolean = False, Optional TabCol As Variant = vbCyan) As Boolean
'=============================================================================
' Check if a sheet exists by an access and create it if not (optional)
Funcname = "Exist_Wsh"
Dim Msgansw As String, Wsh As Worksheet
If IsMissing(Wbk) Then Set Wbk = ActiveWorkbook
On Error GoTo Err_notexist
' Set the default values
Exist_Wsh = False
' Test by access to the sheet, return true if succeeded, or test the Error 9
If Wbk.Worksheets(WshName).Range("A1").Address <> "" Then Exist_Wsh = True
Err_notexist:
' Expected Error raised when accessing to a not existing sheet
If Err.Number = 9 Then
Err.Clear
Msgansw = vbOK
' Create if CreateSh = True with or without user confirmation depending on Prompt_creat
If CreateSh = True Then
If Prompt_creat = True Then
Msgansw = MsgBox("The sheet " & WshName & " doesn't exist" & " in workbbok " & Wbk.Name & vbCrLf & _
"Would you like to create it?", vbExclamation + vbOKCancel, Funcname)
End If
' Create it if not existing depending on users inputs or option
If Msgansw <> vbCancel Or Prompt_creat = False Then
Set Wsh = Wbk.Worksheets.Add(After:=Wbk.Worsheets(Wbk.Worksheets.Count))
Wsh.Name = WshName
Debug.Print VarType(Wsh.Tab.Color)
Wsh.Tab.Color = TabCol
' Test by access to the sheet, return true if succeeded
If Wsh.Range("A1").Address <> "" Then Exist_Wsh = True
End If
End If
Err.Clear
' Return false if another error
Else:
If Err.Number > 0 Then
MsgBox "Error: " & Err.Number & vbCrLf & Err.Description, vbCritical, Funcname
Exist_Wsh = False
Err.Clear
End If
End If
End Function |
Partager