Me encontré teniendo el mismo problema, la necesidad de eliminar datos programáticamente procedentes de Excel diferentes con datos Pivot en caché. Aunque el tema es un poco antiguo, todavía parece que no hay una forma directa de acceder a los datos.
A continuación puede encontrar mi código, que es un refinamiento más generalizado de la solución ya publicada.
La principal diferencia es la eliminación del filtro de los campos, ya que a veces el pivote viene con filtros activados, y si llama a .Showdetail perderá los datos filtrados.
Lo uso para raspar desde diferentes formatos de archivo sin tener que abrirlos, me está sirviendo bastante bien hasta ahora.
Espero que sea útil.
crédito a spreadsheetguru.com en la rutina de limpieza del filtro (aunque no me acuerdo cuánto es original y cuánto es mío para ser honesto)
Option Explicit
Sub ExtractPivotData(wbFullName As String, Optional wbSheetName As_
String, Optional wbPivotName As String, Optional sOutputName As String, _
Optional sSheetOutputName As String)
' This routine extracts full data from an Excel workbook and saves it to an .xls file.
Dim iPivotSheetCount As Integer
Dim wbPIVOT As Workbook, wbNEW As Workbook, wsPIVOT As Worksheet
Dim wsh As Worksheet, piv As PivotTable, pf As PivotField
Dim sSaveTo As String
Application.DisplayAlerts = False
calcOFF
Set wbPIVOT = Workbooks.Open(wbFullName)
' loop through sheets
For Each wsh In wbPIVOT.Worksheets
' if it is the sheet we want, OR if no sheet specified (in which case loop through all)
If (wsh.name = wbSheetName) Or (wbSheetName = "") Then
For Each piv In wsh.PivotTables
' remove all filters and fields
PivotFieldHandle piv, True, True
' make sure there's at least one (numeric) data field
For Each pf In piv.PivotFields
If pf.DataType = xlNumber Then
piv.AddDataField pf
Exit For
End If
Next pf
' make sure grand totals are in
piv.ColumnGrand = True
piv.RowGrand = True
' get da data
piv.DataBodyRange.Cells(piv.DataBodyRange.Cells.count).ShowDetail = True
' rename data sheet
If sSheetOutputName = "" Then sSheetOutputName = "datadump"
wbPIVOT.Sheets(wsh.Index - 1).name = sSheetOutputName
' move it to new sheet
Set wbNEW = Workbooks.Add
wbPIVOT.Sheets(sSheetOutputName).Move Before:=wbNEW.Sheets(1)
' clean new file
wbNEW.Sheets("Sheet1").Delete
wbNEW.Sheets("Sheet2").Delete
wbNEW.Sheets("Sheet3").Delete
' save it
If sOutputName = "" Then sOutputName = wbFullName
sSaveTo = PathWithSlash(wbPIVOT.path) & FilenameNoExtension(sOutputName) & "_data_" & piv.name & ".xls"
wbNEW.SaveAs sSaveTo
wbNEW.Close
Set wbNEW = Nothing
Next piv
End If
Next wsh
wbPIVOT.Close False
Set wbPIVOT = Nothing
calcON
Application.DisplayAlerts = True
End Sub
Sub PivotFieldHandle(pTable As PivotTable, Optional filterClear As Boolean, Optional fieldRemove As Boolean, Optional field As String)
'PURPOSE: How to clear the Report Filter field
'SOURCE: www.TheSpreadsheetGuru.com
Dim pf As PivotField
Select Case field
Case ""
' no field specified - clear all!
For Each pf In pTable.PivotFields
Debug.Print pf.name
If fieldRemove Then pf.Orientation = xlHidden
If filterClear Then pf.ClearAllFilters
Next pf
Case Else
'Option 1: Clear Out Any Previous Filtering
Set pf = pTable.PivotFields(field)
pf.ClearAllFilters
' Option 2: Show All (remove filtering)
' pf.CurrentPage = "(All)"
End Select
End Sub
¿Cuál es el valor en tiempo de ejecución de 'ThisWorkbook. PivotCaches (1) .Recordset'? – shahkalpesh
Es un conjunto de registros con RecordCount = 49, pero si trato de hacer lo siguiente también me sale error definido objeto definido por la aplicación o: Dim objRecordSet Como ADODB.Recordset Set objRecordSet = ThisWorkbook.PivotCaches (1) .Recordset – Kuyenda
Coloque el ThisWorkbook.PivotCaches (1) .Recordset en la ventana de observación para ver qué tipo exacto es. Eso debería ayudar. – shahkalpesh