BigBeachBananas
Active Member
- Joined
- Jul 13, 2021
- Messages
- 450
- Office Version
- 365
- Platform
- Windows
- MacOS
I have a workbook that has 10 tabs, some are hidden, but I don't think it matters for my purpose. On the "SQL" tab, I have a mapping of what I want the new sheet name to be (see A14:B24). I gave cell A15 a named range SheetStart for offsetting purposes in the code. You can ignore everything else on the sheet. When I run my macro, the debug.print sheetName is $200,00 which is correct, but on the next line when I assign "Option 1", it says subscript out of range. Why?
VBA Code:
Dim SheetStart As Range
Dim wb2 As Workbook
Dim sheetName As String
Dim formattedCell As Range
Set SheetStart = wb2.Sheets("SQL").Range("SheetStart")
Set wb2 = ThisWorkbook
wb2.Activate
For i = 1 To 10
' Get the formatted value from the cell
Set formattedCell = SheetStart.Offset(i - 1, 0)
sheetName = formattedCell.Text
' Remove any invalid characters for sheet names
sheetName = Replace(Replace(sheetName, "/", "_"), "\", "_")
' Check if the sheet name is too long (Excel limits sheet names to 31 characters)
If Len(sheetName) > 31 Then
sheetName = Trim(Left(sheetName, 31))
End If
Debug.Print sheetName
Sheets(sheetName).Name = "Option " & i 'subscript error here
Sheets("Summary").Range("Sheet" & i).Value = "Option " & i
Next i