I am perplexed. I have a workbook which is used as a template for parts of the business as a register. The users build a list of register items they are tracking. For each item in the main register I need to create a worksheet that provides more detail on the issue. The new sheets are copies of a template also in the workbook "TemplateCRA". The create action is done using a single macro when all entreis have been made or updated in the register sheet "Ownership"
I started with this which works:
Sub Button1_Click()
'
' Button1_Click Macro
'
Dim MyCell As Range, MyRange As Range
Set MyRange = Sheets("Ownership").Range("B11:B30")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
If IsEmpty(MyCell) Then End
Sheets("TemplateCRA").Copy After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = "CRA Ref " & MyCell.Value ' renames the new worksheet
Range("B6").Value = ActiveSheet.Name
Next MyCell
End Sub
Then I progressed to this in an attempt to ensure that the macro first checks that a sheet has not already been created for the registered item, and if so alerts the user, but then continues to cycle down the items list and creates and new sheets required.
Sub Button2_Click()
'
' Button2_Click Macro
'
Dim MyCell As Range, MyRange As Range
Dim sh As Worksheet, flg As Boolean
Set MyRange = Sheets("Ownership").Range("B11:B30")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each MyCell In MyRange
If IsEmpty(MyCell) Then End
For Each sh In Worksheets
If sh.Name Like "CRA Ref " & MyCell.Value Then flg = True: Exit For
Next
If flg = True Then
MsgBox sh.Name & " Found!"
ElseIf flg = False Then
MsgBox "Creating CRA Ref " & MyCell.Value & " now!"
Sheets("TemplateCRA").Copy After:=Sheets(Sheets.Count) 'creates a new worksheet
Sheets(Sheets.Count).Name = "CRA Ref " & MyCell.Value ' renames the new worksheet
Range("B6").Value = ActiveSheet.Name
End If
Next MyCell
MsgBox "You may now complete your CRA for each item"
End Sub
But this doesnt work properly. What appears to happen is that :
the sh.Name check cycles through OK reporting that sheets are found until it finds an item without a sheet reports a
Run Time error 91 - object variable with block variable not set
in the first MsgBox line.
Can anyone suggest what I have wrong?
Cheers