2015-10-29 51 views
1

我有以下功能,當它返回我電流片的名單運行時錯誤「9」:下標越界訪問表

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':Subsc RIPT超出範圍

什麼是錯我的代碼?

PS:我打電話給下面的方式與功能:

Sub callGetListOfSheetsW() 
    Dim arr() As Variant 
    ' arr = getListOfSheetsW() 
    arr = getListOfSheetsNW() 

    MsgBox arr(1) 
    MsgBox arr(2) 

End Sub 
+1

'For i = 0 To Sheets.Count - 1' as'0' counts。 –

回答

2

工作表數將始終基於一個。

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 
+0

哦,這是學者失誤。謝謝 –