Consulting

Results 1 to 7 of 7

Thread: Need help: debug/fix VBA code to create new worksheets from template and names list

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #4
    Why not sort the range containing the sheet names alphabetically before adding the sheets?
    Alphabetically Sort Cell Range Values With VBA Code (thespreadsheetguru.com)

    EDIT:
    As to the error, this line
    ws.Name = rngLoop.Value
    is giving the error because rngLoop.Value equals "". A sheet must have a name. This statement
    Set rng = .Range("B2", "B" & .Cells(Rows.Count, "B").End(xlUp).Row)
    is returning 19 cells (screenshot https://imgur.com/E9O0J4R) because of the If statement in the formula. You can add
    If rngLoop.Value = "" Then Exit For
    under the For each line to stop looping when you encounter this.

    EDIT2: the code that works for me
        Dim rng As Range, rngLoop As Range, ws As Worksheet, lo As ListObject
        
        'Create new worksheets from names in first column of aa_Master worksheet
        With ActiveWorkbook.Sheets("aa_Master")
            Set lo = .ListObjects(1)  ' the data in this sheet is a table
            lo.Range.Sort key1:=Range("B2")
        
            Set rng = .Range("B2", "B" & .Cells(Rows.Count, "B").End(xlUp).Row)
            For Each rngLoop In rng
                If rngLoop.Value = "" Then Exit For   ' a cell that is blank has been encountered, end the loop
                If Not SheetExists(rngLoop.Value) Then
                    ActiveWorkbook.Sheets("aa_Template").Copy after:=ActiveWorkbook.Sheets(ActiveWorkbook.Sheets.Count)
                    Set ws = ActiveSheet
                    ws.Name = rngLoop.Value
                Else
                    Set ws = ActiveWorkbook.Sheets(rngLoop.Value)
                End If
            Next
            .Activate
        End With
    Last edited by jdelano; 09-10-2023 at 04:00 AM.

Posting Permissions

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