【问题标题】:"Workbook.Sheets.Add After" gives "Subscript out of range" error (VBA)“Workbook.Sheets.Add After”给出“下标超出范围”错误(VBA)
【发布时间】:2015-05-13 10:48:36
【问题描述】:

我有一个包含四张纸的工作簿 - FirstSecondThirdFourth。我试图在每张表之后添加一张额外的表来创建数据透视表。它们将被命名为First PivotSecond PivotThird PivotFourth Pivot

我能够创建 First Pivot 工作表,但出现 Subscript out of range 错误。我使用的代码是

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 进行了检查)。

谁能告诉我我做错了什么?

【问题讨论】:

  • 此代码对我有效,直到所有现有工作表都包含一些数据。我之所以说一些数据,是因为如果工作表中没有数据,.Find 将失败。我已经解释了Here 在该链接中查看Application.WorksheetFunction.CountA(.Cells) &lt;&gt; 0 的使用

标签: excel vba


【解决方案1】:

改变这个:

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

到这里:

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

我可以看到您收到该错误的唯一方法是代码位于某个位置(例如 ThisWorkbook 模块),其中 Worksheets(CurrSheet.Index) 本身指的是带有代码的工作簿而不是 NewBook。 (除此之外:在这种情况下它确实可以正常工作很奇怪,但是直到提供的索引高于包含代码的工作簿中的工作表数)无论如何,最好还是指定工作簿。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-05-27
    • 2017-06-16
    • 2014-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多