Home » excel » excel – VBA can't get array to resize

excel – VBA can't get array to resize

Posted by: admin April 23, 2020 Leave a comment


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

For Each element In sheetsForCalendar
    MsgBox (sheetsForCalendar(element))
How to&Answers:

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

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

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).


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