我试图让我的数组调整到我的工作簿中工作表数量的长度,但不断得到
对于上下文,我的工作表名称是“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
最佳答案
除了代码中的其他问题外,这里是错误的:
For Each element In sheetsForCalendar
MsgBox (sheetsForCalendar(element))
Next
element
采用sheetForCalendar 中的值,即。 2015
, 2016
例如,它不是索引。要么循环
for n = 0 to UBound(sheetsForCalendar)
要么只是 MsgBox element
。您应该阅读如何单步执行代码(F8 并将光标放在变量上以查看其内容)。这将帮助您轻松找到您的错误(以及您如何像 Mark Snyder 指出的那样“错误对待”
i
)。关于VBA 无法让数组调整大小,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/35397657/