Excel VBA loop to make an array of wokrsheet names

WTC_Services
WTC_Services used Ask the Experts™
on
Hi,
I'm trying to make an array that is a list of all the worksheet names in my excel document, this script seems close but doesn't quite work, instead it lists a seriies of references to various cells, can you please help?

Sub Worksheet_define()

Dim WSheets() As String
Dim iCount As Integer
Dim Max As Integer
    Max = ThisWorkbook.Sheets.Count
    ReDim WSheets(1 To Max)
    For iCount = 1 To Max
        WSheets(iCount) = ThisWorkbook.Names(iCount)
    Next iCount

End Sub

Thanks, WTC
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Most Valuable Expert 2012
Top Expert 2012

Commented:
Try

WSheets(iCount) = ThisWorkbook.Names(iCount).Name
Try:

Sub Worksheet_define()

Dim WSheets() As Variant
Dim iCount As Integer
Dim Max As Integer
    Max = ThisWorkbook.Worksheets.count
    ReDim WSheets(1 To Max)
    For iCount = 1 To Max
        WSheets(iCount) = ThisWorkbook.Worksheets(iCount).Name
    Next iCount

End Sub
Try changing

ThisWorkbook.Names(iCount)

to

Sheets(iCount).name
OWASP: Threats Fundamentals

Learn the top ten threats that are present in modern web-application development and how to protect your business from them.

Most Valuable Expert 2012
Top Expert 2012

Commented:
Actually you want:

wSheets(iCount) = Thisworkbook.Worksheets(iCount).name.

Here's the way I do it, a bit differently, however:

Sub Worksheet_define()
Dim WSheets() As String
Dim iCount As Integer
Dim Max As Integer
Dim wks As Worksheet

    For Each wks In ThisWorkbook.Worksheets
        ReDim Preserve WSheets(iCount) As String
        WSheets(iCount) = wks.Name
        iCount = iCount + 1
    Next wks
   

End Sub
And yet another alternative  

Using a dictionary object  (add reference to the Microsoft Scripting Runtime via Tools/References)

Sub Worksheet_define()
  Dim ws as Worksheet
  Dim d as New Dictionary

  For Each ws in ThisWorkbook.Worksheets
    d(ws.Name) = ""
  Next ws

End Sub

Most Valuable Expert 2012
Top Expert 2012

Commented:
Very strange that you did not choose mikeopolo's suggested post.  It appears exactly correct, and was posted earlier than the one you selected.

In addition, using Sheets(iCount).name does not appear 100% correct, if your Excel workbook contains chart tabs - they would not be included in your array of names.  Also, if the ActiveWorkbook were not ThisWorkbook, you'd get the wrong list of sheet names :)

Cheers,

Dave

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial