J'essaye de créer un pivot dans Excel via VBA, mais je n'arrive pas à comprendre pourquoi ce code ne fonctionne pas. Il n'y a pas d'erreur - il n'y a tout simplement pas de tableau croisé dynamique créé. J'ai utilisé exactement ce même code dans d'autres programmes sans problème (en remplaçant évidemment les variables locales). J'ai déjà confirmé que mes données sources sont correctement définies. Ma seule piste est qu'après avoir exécuté la création du cache pivot, cela montre que PvtCache = Nothing.Comment s'assurer que PivotCache fonctionne correctement?
Option Explicit
Sub Create_Report()
Dim sht_Break_Data As Worksheet
Dim sht_Num_Breaks_Pvt As Worksheet
Dim tab_name As String
Dim lrow_Src As Long
Dim lcol_Src As Long
Dim rng_Pvt_Source As Range
Dim PvtStart As Range
Dim PvtCache As PivotCache
Dim Pvt As PivotTable
Dim PvtField As PivotField
Dim PvtName As String
Set_Global_Variables
'Get last row and column of Source Data Tab
With sht_Source_Data
lrow_Src = .Cells(Cells.Rows.Count, 1).End(xlUp).Row
lcol_Src = .Cells(1, Cells.Columns.Count).End(xlToLeft).Column
'Set source data range for pivots
Set rng_Pvt_Source = .Range(.Cells(1, 1), .Cells(lrow_Src, lcol_Src))
End With
'=======================================Create Pivot for Number of Breaks==========================================='
'Create sheet for Number of Breaks Pivot
'If the given tab name already exists, contents are deleted. If not, it is created
With ThisWorkbook
tab_name = "Num of Breaks Pivot"
If SheetExists(tab_name, ThisWorkbook) = True Then
Set sht_Num_Breaks_Pvt = .Sheets(tab_name)
On Error Resume Next
sht_Num_Breaks_Pvt.ShowAllData 'clear any active filter
sht_Num_Breaks_Pvt.Cells.Delete 'delete content
Else
.Sheets.Add(After:=.Sheets(.Sheets.Count)).Name = tab_name 'add new tab to the end
Set sht_Num_Breaks_Pvt = .Sheets(tab_name)
End If
'Define pivot start location
Set PvtStart = sht_Num_Breaks_Pvt.Cells(2, 1)
'Create Pivot Cache from Source Data
Set PvtCache = .PivotCaches.Create(_
SourceType:=xlDatabase, _
SourceData:=rng_Pvt_Source)
'Create Pivot table from Pivot cache
Set Pvt = PvtCache.CreatePivotTable(_
TableDestination:=PvtStart, _
TableName:="test")
End With
End Sub
Juste une intuition: passez par le code ligne par ligne en utilisant F8, et vérifiez que sht_Num_Breaks_Pvt est en train d'être mis à la feuille que vous pensez qu'il est. – jeffreyweir
Déjà vérifié en imprimant le nom de la feuille, et c'est correct. – kschindl
D'accord. Pouvez-vous ajouter cela à la fin de la routine, et revenir sur ce qui se passe? msgbox pvt.parent.name & "" & pvt.name – jeffreyweir