You are here:

# Excel/Loop for naming the sheet's

Question
Hi Tom,

I'm trying to name the sheet as "Combination1" to "Combination50". If Combination1 sheet is already existing then it will take the name as Combination2..till Combination50.

I have the below code but facing some problem -

Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook

Dim q As String
Dim u As Integer

q = ""
For u = 1 To 50
q = "Combination" & u
If Not SheetExists(q) Then
ws.Name = q

End If

Next u
end sub

Function SheetExists(SheetName As String) As Boolean
' returns TRUE if the sheet exists in the active workbook
SheetExists = False
On Error GoTo NoSuchSheet
If Len(Sheets(SheetName).Name) > 0 Then
SheetExists = True
Exit Function
End If
NoSuchSheet:
End Function

Please check and let me know where am i wrong.

Lucky,

I assume your intent is to add only one sheet and then give it the name combination with the next available number added to the root name combination.  If so then you just have a logic problem.

Dim wb As Workbook
Dim ws As Worksheet

Set wb = ThisWorkbook

Dim q As String
Dim u As Integer

q = ""
For u = 1 To 50
q = "Combination" & u
If Not SheetExists(q) Then
ws.Name = q
Exit Sub  ' <= quit looking for a name
End If

Next u
End Sub

Function SheetExists(SheetName As String) As Boolean
' returns TRUE if the sheet exists in the active workbook
SheetExists = False
On Error GoTo NoSuchSheet
If Len(Sheets(SheetName).Name) > 0 Then
SheetExists = True
Exit Function
End If
NoSuchSheet:
End Function

so that code worked for me as I understand your requirement.

--
Regards,
Tom Ogilvy
Questioner's Rating
 Rating(1-10) Knowledgeability = 10 Clarity of Response = 10 Politeness = 10 Comment Thank you Sooo Much Tom!

This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here

#### Tom Ogilvy

##### Expertise

Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]

##### Experience

Extensive experience.

Education/Credentials
Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.