3

I am trying to get my array to resize to the length of the number of sheets in my workbook but keep getting

Subscript out of range

For context my sheet names are "Year XXXX"

Dim sheetsForCalendar() As Integer    

For Each Worksheet In ThisWorkbook.Sheets
    Dim i As Integer: i = 0
    Dim calendarYear() As String: calendarYear() = Split(CStr(Worksheet.Name))
    ReDim Preserve sheetsForCalendar(i)

    If calendarYear(0) = "Year" Then
        Dim calendarYearAsInt As Integer: calendarYearAsInt = calendarYear(1)
        sheetsForCalendar(i) = calendarYearAsInt
    End If

    i = i + 1
Next

For Each element In sheetsForCalendar
    MsgBox (sheetsForCalendar(element))
Next
1
  • I am using ReDim, (see line 5) and still getting the error. Commented Feb 14, 2016 at 20:44

2 Answers 2

1

Beside other problems in your code, this here is wrong:

For Each element In sheetsForCalendar
    MsgBox (sheetsForCalendar(element))
Next

element takes the values in sheetsForCalendar, ie. 2015, 2016 for example, it is not the index.
Either loop through for n = 0 to UBound(sheetsForCalendar) or just MsgBox element.

You should read on how to single-step through your code (F8 and place cursor over variables to see their content). This will help you find your errors easily (also how you 'mistreated' i as Mark Snyder pointed out).

Sign up to request clarification or add additional context in comments.

Comments

1

I believe the problem is that you set i = 0 at the beginning of your For Each loop, so no matter how many sheets you have, the ReDim statement always uses the value 0. If you move the Dim statement for variable i above the For Each statement, it should work better. HTH

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.