I am working on a piece of code that creates a copy of a certain Template sheet or deletes a sheet based on the contents of a column in an Excel Sheet, starting in cell B2.
Actions I would like the Macro to do:
1) If a sheet name matches an array value do nothing
2) If there is no sheet for an array value, create a copy of the Template sheet and rename with the array value. Further, name cell A1 of the copied sheet as the array value.
3) If there is a sheet that does not exist in the array, delete the sheet. Except for the sheets named Input or Template.
Up to now I have two separate codes, one to copy sheets and the other to delete sheets:
Code in order to add sheets:
Sub AddSheet()
Application.ScreenUpdating = False
Dim bottomA As Integer
bottomA = Range("A" & Rows.Count).End(xlUp).Row
Dim c As Range
Dim ws As Worksheet
For Each c In Range("A1:A" & bottomA)
Set ws = Nothing
On Error Resume Next
Set ws = Worksheets(c.Value)
On Error GoTo 0
If ws Is Nothing Then
Sheets("Template").Select
Sheets("Template").Copy After:=Sheets(Sheets.Count)
ActiveSheet.name = c.Value
End If
Next c
Application.ScreenUpdating = True
End Sub
Code in order to delete sheets:
Sub DeleteSheet()
Dim i As Long, x, wsAct As Worksheet
Set wsAct = ActiveSheet
For i = Sheets.Count To 1 Step -1
If Not Sheets(i) Is wsAct Then
x = Application.Match(Sheets(i).name, wsAct.Range("A1:A20"), 0)
If IsError(x) Then
Application.DisplayAlerts = False
Sheets(i).Delete
Application.DisplayAlerts = True
End If
End If
Next i
End Sub
My questions are:
1) How can I add the piece that renames cell A1 with the array value in the AddSheet code?
2) How can I add the except rules in the DeleteSheet code?
3) How can I combine these codes into one code and finally create a button to activate this macro in the Input sheet?
Many thanks in advance!