第一次执行此功能时,它可以正常工作。第二次执行某些设置更改与此代码无关时,我得到运行时错误1004
With PT.PivotFields("Group")
For i = LBound(GroupNames) To UBound(GroupNames)
.PivotItems(GroupNames(i)).Position = i + 1
Next i
End With
这是函数,
Public Sub Create_Pivots_Calculation()
Dim PT As PivotTable
Dim PC As PivotCache
Dim PTRng As Range
Dim WSTemp As Worksheet, WSSummary As Worksheet
Dim i As Integer
Set PTRng = Range("Rate_Data") 'Pivot table range
Set ECARDataRangeCalc = Range("Range_ECAR_Data") 'Where OCRTable begins to be added
Set WSTemp = Sheets.Add 'The new empty sheet
Set WSSummary = Sheets("Summary Printout") 'The output sheet
Set PC = ThisWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=PTRng)
With WSTemp
'Create a pivot table with the Rate data.
'we are recreating the data with group and Well as the column and time as the row for calculation.
Set PT = .PivotTables.Add(PivotCache:=PC, TableDestination:=.Range("A100"))
PT.ErrorString = 0
PT.DisplayErrorString = True
With PT
.ColumnGrand = False
.RowGrand = False
.PivotFields("Group").Orientation = xlColumnField
.PivotFields("Well").Orientation = xlColumnField
.PivotFields("Time").Orientation = xlRowField
PT.AddDataField PT.PivotFields("ECAR"), "Average", xlAverage
'Hide the Background group
On Error Resume Next
.PivotFields("Group").PivotItems("Background").Visible = False
On Error GoTo 0
'Use average of ECAR in the data field
'Sort the pivot as per the selected group order in the GUI
With PT.PivotFields("Group")
For i = LBound(GroupNames) To UBound(GroupNames)
.PivotItems(GroupNames(i)).Position = i + 1
Next i
End With
'Clear the existing range for all data
WSSummary.Range(ECARDataRangeCalc, ECARDataRangeCalc.Offset(100, 0)).EntireRow.ClearContents
'Paste the new data in the OCR Data range
.TableRange1.Offset(1, 0).Resize(rowsize:=.TableRange1.Rows.Count - 1).Copy ECARDataRangeCalc
ECARDataRangeCalc = "Time (min)"
Set ECARDataRangeCalc = ECARDataRangeCalc.CurrentRegion 'Reset the OCRDataRange
Set ECARDataRangesCalc(0) = ECARDataRangeCalc
'On the basis of OCRDataRange build the OCRDataRange for next summary - this will be after one column where OCRDataRange ends
Set ECARDataRangeCalc = ECARDataRangeCalc.Offset(0, ECARDataRangeCalc.Columns.Count + 1)
End With
'Delete the temp sheet
Application.DisplayAlerts = False
.Delete
Application.DisplayAlerts = True
End With
Set PC = Nothing
Set PT = Nothing
End Sub
任何帮助表示赞赏!!!
答案 0 :(得分:0)
更改行:
Set PT = .PivotTables.Add(PivotCache:=PC, TableDestination:=.Range("A100"))
到
Set PT = .PivotTables.Add(PivotCache:=PC, TableDestination:=WSTemp.Range("A100"))
为您解决问题?