2015-10-20 63 views
0

Im在這個論壇上新的。我想問問有沒有人可以幫助我。我編寫了一個宏,它可以更改所有的pivottables源,如果pt的名稱以1結尾,它將從另一個xlsx文件應用一個源,並且如果它的2從另一個文件中給出另一個源。我在宏觀期間將這兩本書都保持開放,以確保它在這一方面不會中斷。但是在「情況2」中,它總是拋出運行時錯誤13:類型錯配。誰能幫我解決這個問題。手前謝謝!運行時錯誤13 - 改變pivotcache

Sub origen_tablas_fwb() 

Dim hoja As Worksheet 
Dim pt As PivotTable 
Dim a1, a2, j As Long 
Dim libro1, libro2 As String 

a2 = Workbooks("Global ETdlc.xlsx").Worksheets("Comando").Range("A7").Value 
a1 = a2 - 1 
Windows("Global ETdlc.xlsx").Activate 
Sheets("Comando").Activate 
j = Sheets("Comando").Range("N1", Range("N1").End(xlDown)).Rows.Count 
libro2 = Workbooks("Global ETdlc.xlsx").Worksheets("Comando").Range("B8").Value 
For i = 1 To j 
    If Cells(i, 14).Value = libro2 Then 
    libro1 = Cells(i, 15).Value 
    End If 
Next i 

'Workbooks.Open Filename:="C:\Respaldo Reservas\FEEDS+FWB\" & a1 & "\" & libro1 
'Workbooks.Open Filename:="C:\Respaldo Reservas\FEEDS+FWB\" & a2 & "\" & libro2 

'Workbooks.Open Filename:="C:\Informes\Forward Bookings" 
Windows("Forward Bookings").Activate 
For Each hoja In ActiveWorkbook.Worksheets 
    For Each pt In Worksheets(hoja.Name).PivotTables 
     Select Case Right(pt.Name, 1) 
     Case 1 
     'cambiar cache año anterior 
     ActiveSheet.pt.ChangePivotCache ActiveWorkbook. _ 
     PivotCaches.Create(SourceType:=xlDatabase, _ 
     SourceData:=Workbooks(libro1).Sheets("Input").Range("A1").CurrentRegion) 
     Case 2 
     'cambiar cache año actual 
     ActiveSheet.pt.ChangePivotCache ActiveWorkbook. _ 
     PivotCaches.Create(SourceType:=xlDatabase, _ 
     SourceData:=Workbooks(libro2).Sheets("Input").Range("A1").CurrentRegion) 
     End Select 
    Next pt 
Next hoja 
Windows(libro1).Close 
Windows(libro2).Close 
End Sub 

回答

0

的代碼實際上是試圖爲每個PivotTable一個PivotCache

我建議每個外部工作簿只創建一個PivotCache,然後更改每個PivotTable所對應的PivotCache

替換您與此代碼更改透視緩存部分:

Dim Pch1 As PivotCache, Pch2 As PivotCache 

With Windows("Forward Bookings") 
    With .PivotCaches 
     Set Pch1 = .Create(SourceType:=xlDatabase, _ 
      SourceData:=Workbooks(libro1).Sheets("Input").Range("A1").CurrentRegion) 
     Set Pch1 = .Create(SourceType:=xlDatabase, _ 
      SourceData:=Workbooks(libro2).Sheets("Input").Range("A1").CurrentRegion) 
    End With 
    For Each hoja In .Worksheets 
     For Each pt In hoja.PivotTables 
      Select Case Right(pt.Name, 1) 
      Case 1 
       'cambiar cache año anterior 
       pt.ChangePivotCache (Pch1) 
      Case 2 
       'cambiar cache año actual 
       pt.ChangePivotCache (Pch2) 
      End Select 

Next: Next: End With