VBA无法获取数组来resize

我试图让我的数组调整到我的工作簿中的张数的长度,但不断得到

下标超出范围

对于上下文我的表名是“年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 

除了代码中的其他问题,这里是错误的:

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

element采用sheetsForCalendar中的值,即。 20152016 ,例如,它不是索引。
或者循环遍历for n = 0 to UBound(sheetsForCalendar)或者只是MsgBox element

您应该阅读如何单步执行代码(F8并将光标置于variables上以查看其内容)。 这将帮助你轻松find你的错误(也就是你像马克·斯奈德(Mark Snyder)指出的那样“虐待你”)。

我相信问题是你在For Each循环的开始处设置了i = 0,所以无论你有多less张表,ReDim语句总是使用值0.如果你将Dim语句移到了For每一个声明,它应该更好地工作。 HTH