" Workbook.Sheets.Add After"给出"下标超出范围"错误(VBA)

时间:2015-05-13 10:48:36

标签: excel-vba vba excel

我的工作簿有四张 - 第一个第二个第三个​​第四个。我尝试在每张工作表后添加一张额外的工作表来创建数据透视表。它们将被命名为 First Pivot Second Pivot Third Pivot Fourth Pivot

我能够创建 First Pivot 表,但我收到 下标超出范围 错误。我使用的代码是

Function Pivotizer(FilePathAndName As String)
  On Error GoTo ErrorTeller
  Dim NewBook As Workbook, CurrSheet, sht As Worksheet, i, FinalCol, ColIndex As Integer, FinalRow As Long
  Dim pvtCache As PivotCache, pvt As PivotTable, StartPvt, SrcData, KountOf As String

  Set NewBook = Workbooks.Open(FilePathAndName )


  For Each CurrSheet In NewBook.Worksheets
    FinalRow = CurrSheet.Cells.Find(What:="*", After:=CurrSheet.Cells(1, 1), LookIn:=xlFormulas, LookAt:= _
                xlPart, SearchOrder:=xlByRows, SearchDirection:=xlPrevious, MatchCase:=False).Row
    FinalCol = CurrSheet.Cells(1, CurrSheet.Columns.Count).End(xlToLeft).Column

If CurrSheet.Name = "First" Then

  NewBook.Sheets.Add After:=Worksheets(CurrSheet.Index)
  NewBook.Sheets(CurrSheet.Index + 1).Name = "First Pivot"

ElseIf CurrSheet.Name = "Second" Then
  NewBook.Sheets.Add After:=Worksheets(CurrSheet.Index)'<--- This is where I get the error
  NewBook.Sheets(CurrSheet.Index + 1).Name = "Second Pivot"
End If
  Next
  Exit Function
ErrorTeller:
  MsgBox Err.Description
End Function

出于某种原因, CurrSheet.Index 似乎没有第二次工作,虽然它代表一个有效的数字(我使用MsgBox检查)

有人可以告诉我,我做错了吗?

1 个答案:

答案 0 :(得分:1)

改变这个:

NewBook.Sheets.Add After:=Worksheets(CurrSheet.Index)

到此:

NewBook.Sheets.Add After:=NewBook.Worksheets(CurrSheet.Index)

我能看到你得到该错误的唯一方法是,如果代码位于某个位置(例如ThisWorkbook模块),其中Worksheets(CurrSheet.Index)本身引用带有代码的工作簿而不是NewBook。 (旁白:奇怪的是它在所有情况下都能正常工作,但直到提供的索引高于包含代码的工作簿中的工作表数量才会这样做)无论如何,最好还是指定工作簿。