【发布时间】:2015-05-13 10:48:36
【问题描述】:
我有一个包含四张纸的工作簿 - First、Second、Third 和 Fourth。我试图在每张表之后添加一张额外的表来创建数据透视表。它们将被命名为First Pivot、Second Pivot、Third Pivot和Fourth 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) <> 0的使用