0
votes

I have created a worksheets from a range using this code (which is working for me)

Sub AddSheets1()

Dim cell As Excel.Range
Dim wsWithSheetNames As Excel.Worksheet
Dim wbToAddSheetsTo As Excel.Workbook
Set wsWithSheetNames = ActiveSheet
Set wbToAddSheetsTo = ActiveWorkbook
Dim xlWs1 As Worksheet

Set xlWs1 = Worksheets("template")
Set Rng1 = xlWs1.Range("A1:AR2")

For Each cell In wsWithSheetNames.Range("G3:G5") 'user to change this value when list is updated
    With wbToAddSheetsTo
        .Sheets.Add after:=.Sheets(.Sheets.Count)
        On Error Resume Next
        ActiveSheet.Name = cell.Value

        Set xlWs2 = Worksheets(CStr(cell.Value))
        Set Rng2 = xlWs2.Range("A1")
        Rng1.Copy Rng2

        If Err.Number = 1004 Then
          Debug.Print cell.Value & " already used as a sheet name"
        End If
        On Error GoTo 0
    End With
Next cell

End Sub

So now, I want to assign the newly created worksheets with variables. (so that I can further manipulate using ws1, ws2 etc. Something like

Dim i As Integer, n As Integer
n = wsWithSheetNames.Range("G3:G5").Count
ReDim ws1(1 To n)
For i = 1 To n
    Set ws1(i) = ThisWorkbook.Worksheets(i)
Next

How do I assign the worksheet name to the names that I've created from the range?

1
Perhaps small change in the line: Set ws1(i) = ThisWorkbook.Worksheets(i) to: Set ws1 & i = ThisWorkbook.Worksheets(i) should work for you.1001001
@1001001, the code doesnt work and throws an error when savingHwee7

1 Answers

0
votes

Assuming there may be more sheets than what's specified in G3:G5, maybe this will work.

Dim r As Range, c As Range, x As Long
Set r = wsWithSheetNames.Range("G3:G5").SpecialCells(xlCellTypeConstants)
ReDim ws1(1 To r.Count)
For Each c In r
  x = x + 1
  Set ws1(x) = ThisWorkbook.Worksheets(c.Value)
Next c