+ Reply to Thread
Results 1 to 2 of 2

Thread: Code Required To Avoid Error on Worksheet Insert

  1. #1
    Registered User
    Join Date
    01-06-2012
    Location
    Sherwood Park, Alberta
    MS-Off Ver
    Excel 2010
    Posts
    1

    Code Required To Avoid Error on Worksheet Insert

    Worksheet Title: "Summary"
    Column A, starting in row 2:
    A
    B
    C
    D

    The code below effectively creates and renames four (4) worksheets "A", "B", "C" and "D". But, if I add a row with "E" and run the macro, I get an error basically saying A, B, C and D already exist so you are screwed....

    I need to insert code that will allow me to create only new worksheets for the new data in column A. Thank you so much for your help.

    Sub CreateSheetsFromAList()
        Dim MyCell As Range, MyRange As Range
        
        Set MyRange = Sheets("Summary").Range("A2")
        Set MyRange = Range(MyRange, MyRange.End(xlDown))
    
        For Each MyCell In MyRange
            Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
            Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
        Next MyCell
    End Sub
    Last edited by DonkeyOte; 01-06-2012 at 03:01 PM. Reason: CODE tags please (per Rules) - amended (1st post)

  2. #2
    Forum Moderator DonkeyOte's Avatar
    Join Date
    10-22-2008
    Location
    Suffolk, UK
    MS-Off Ver
    2002, 2007 & 2010
    Posts
    21,423

    Re: Code Required To Avoid Error on Worksheet Insert

    Please use CODE tags when posting VBA to the board.

    In answer to your question - validate existence of sheet prior to addition:

    Sub CreateSheetsFromAList()
        Dim MyCell As Range, MyRange As Range    
        Set MyRange = Sheets("Summary").Range("A2")
        Set MyRange = Range(MyRange, MyRange.End(xlDown))
        For Each MyCell In MyRange
            If Not Evaluate("ISREF('" & MyCell.Value & "'!A1)") Then
                Sheets.Add After:=Sheets(Sheets.Count) 'creates a new worksheet
                Sheets(Sheets.Count).Name = MyCell.Value ' renames the new worksheet
            End If
        Next MyCell
    End Sub

+ Reply to Thread

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.2.0