1

I have following function which returns me list of current sheets

Function getListOfSheetsW() As Variant Dim i As Integer Dim sheetNames() As Variant ReDim sheetNames(1 To Sheets.Count) For i = 1 To Sheets.Count sheetNames(i) = Sheets(i).name Next i getListOfSheetsW = sheetNames End Function 

This function returns array starting at position 1. My goal was to create same function but starting with position 0, I've tried:

Function getListOfSheetsNW() As Variant Dim i As Integer Dim sheetNames() As Variant ReDim sheetNames(Sheets.Count - 1) For i = 0 To Sheets.Count sheetNames(i) = Sheets(i + 1).name Next i getListOfSheetsNW = sheetNames End Function 

But this return me:

Run-time error '9': Subscript out of range

What is wrong with my code?

PS: I'm calling those functions following way:

Sub callGetListOfSheetsW() Dim arr() As Variant ' arr = getListOfSheetsW() arr = getListOfSheetsNW() MsgBox arr(1) MsgBox arr(2) End Sub 
1
  • 1
    For i = 0 To Sheets.Count - 1 as 0 counts. Commented Oct 29, 2015 at 17:37

1 Answer 1

2

The worksheet count will always be one based.

Function getListOfSheetsNW() As Variant Dim i As Integer Dim sheetNames() As Variant ReDim sheetNames(Sheets.Count - 1) For i = 0 To Sheets.Count - 1 '<~~This. Alternately as For i = 0 To UBound(sheetNames) sheetNames(i) = Sheets(i + 1).name Next i getListOfSheetsNW = sheetNames End Function 
Sign up to request clarification or add additional context in comments.

1 Comment

Oh, this was scholar mistake. Thank you

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.