[英]Run-time error '9': Subscript out of range when accessing Sheets
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: 此函数返回从位置1开始的数组。我的目标是创建相同的函数,但从位置0开始,我尝试过:
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
运行时错误“ 9”:下标超出范围
What is wrong with my code? 我的代码有什么问题?
PS: I'm calling those functions following way: PS:我通过以下方式调用这些函数:
Sub callGetListOfSheetsW()
Dim arr() As Variant
' arr = getListOfSheetsW()
arr = getListOfSheetsNW()
MsgBox arr(1)
MsgBox arr(2)
End Sub
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.