Consulting

Results 1 to 2 of 2

Thread: Create worksheets from a list

  1. #1

    Create worksheets from a list

    Hi all I have a vba script that creates tabs from a worksheet called "Query". It starts from A2 (worksheet name) and B2 (the sql connection string to use).

    The script runs fine if I have the same number of tabs and their names are unchanged. But crashes when I add a new row to the Query but I can get around it by deleting all the sheets in the list but I don't want to do it.

    Any fixes?

    Sub CreateTab()
    
    Dim sh As Worksheet, flg As Boolean
    Dim i As Integer
    Dim r As Range
    Dim shName As String
    
    
    Sheets("Query").Select
    ActiveSheet.Range("a1").Select
    
    
    'Count the end row
    i = Selection.End(xlDown).Row
    
    'Loop from A2 to A(i) to Create Sheets
    For Each r In Range("a2:a" & i)
        For Each sh In Worksheets
            If sh.Name = r.Value Then flg = True: Exit For
            Next
                If flg = True Then
                    Sheets("Query").Select
                    ActiveSheet.Range("a1").Select
                Else
                Sheets.Add.Name = r.Value
                End If
        ActiveSheet.Move after:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
    Next
    
    Sheets("Query").Select
    ActiveSheet.Range("a2").Select
     
    End Sub

  2. #2
    VBAX Expert CatDaddy's Avatar
    Joined
    Jun 2011
    Posts
    581
    Location
    your flg logic is a little confusing, but i have a few suggestions:

    [VBA]For each sh in ActiveWorkbook.Worksheets[/VBA]

    [VBA]If sh.Name = r.Value Then Exit For
    Else
    Sheets.Add.Name = r.Value
    End If
    [/VBA]
    ------------------------------------------------
    Happy Coding my friends

Posting Permissions

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