[英]Run-time error '9': Subscript out of range when accessing 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
此函數返回從位置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
但這返回了我:
運行時錯誤“ 9”:下標超出范圍
我的代碼有什么問題?
PS:我通過以下方式調用這些函數:
Sub callGetListOfSheetsW()
Dim arr() As Variant
' arr = getListOfSheetsW()
arr = getListOfSheetsNW()
MsgBox arr(1)
MsgBox arr(2)
End Sub
工作表計數將始終基於一個。
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.