Good afternoon all!
I've been trying to tweak this code, based on other posts i saw around, similar to this situation.
I use the macro to copy/paste the template sheet and it names the new sheet according to a code and the number it stores on cell H2 of the template. This number increments but the rest stays the same.
The problem is, I need it to return to zero or the previous number if I delete sheets.
For example, the name of the sheets created is ORC01_R0 and if i create a new one, it names the new sheet ORC02_R0. (if others are added, then ORC03_R0, ORC04_R0 and so on)
If i delete all sheets created, the name of a newly created sheet will be ORC01_R0.
If I only delete ORC02_R0, then the next sheet should be ORC02_R0, because the previous one is ORC01_R0.
My code currently keeps the last number used and doesn't return to zero if i delete all sheets, or to the previous number if the sheet name doesn't exist.
All suggestions are welcome!
I've been trying to tweak this code, based on other posts i saw around, similar to this situation.
I use the macro to copy/paste the template sheet and it names the new sheet according to a code and the number it stores on cell H2 of the template. This number increments but the rest stays the same.
The problem is, I need it to return to zero or the previous number if I delete sheets.
For example, the name of the sheets created is ORC01_R0 and if i create a new one, it names the new sheet ORC02_R0. (if others are added, then ORC03_R0, ORC04_R0 and so on)
If i delete all sheets created, the name of a newly created sheet will be ORC01_R0.
If I only delete ORC02_R0, then the next sheet should be ORC02_R0, because the previous one is ORC01_R0.
My code currently keeps the last number used and doesn't return to zero if i delete all sheets, or to the previous number if the sheet name doesn't exist.
VBA Code:
Sub NewNum()
' This macro assumes that there is a worksheet named "Template"
' and that worksheet contains the current sheet number in cell H2.
Dim i As Long, temp As String
Dim iNextNum As Long
Dim ws As Worksheet
Dim REV As Variant
Dim Year As String, wsName As String
Year = DatePart("YYYY", Date)
On Error GoTo 0
Set ws = Sheets("Template")
ws.Visible = xlSheetVisible
REV = ws.Range("I2").Value
With Sheets("Template").Range("H2")
iNextNum = .Value + 1
.Value = iNextNum
End With
wsName = "ORC" & Format(iNextNum, "0") & "-" & Right(Year, 2) & "_R" & REV
If WorksheetExists(wsName) Then
temp = wsName
i = 1
wsName = temp & i
Do While WorksheetExists(wsName)
i = i + 1
wsName = temp & i
Loop
End If
Sheets("Template").Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = wsName
ws.Range("I2").Value = i
ws.Visible = xlSheetHidden
End Sub
Function WorksheetExists(wsName As String) As Boolean
On Error Resume Next
WorksheetExists = Worksheets(wsName).Name = wsName
On Error GoTo 0
End Function
All suggestions are welcome!