访问表格时,运行时错误' 9':下标超出范围

时间:2015-10-29 17:34:14

标签: excel vba excel-vba

我有以下功能,它返回当前工作表的列表

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

1 个答案:

答案 0 :(得分: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