Public Sub CreatePivotTable()
Dim wb As Workbook ’聲明3個變量!
Dim pt As PivotTable
Dim pc As PivotCache
On Error GoTo ErrorHandler
‘ Open the workbook.即設置打開壹個工作簿的變量。
Set wb = Workbooks.Open(“c:\PivotData\RawData.xls”)
‘ Create the PivotCache.創建壹個透視表內存緩存!
Set pc = wb.PivotCaches.Add(SourceType:=xlDatabase, SourceData:=”[RawData.xls]Sheet1!A4:C28”)
‘ 采用CreatePivotTable方法,利用透視表緩存創建壹個數據透視表!
Set pt = pc.CreatePivotTable TableDestination:=”[RawData.xls]Sheet2! “,TableName:=”Data”
‘下面是錯誤處理程序!
wb.Worksheets(“Sheet2”).Activate
EndOfSub:
Exit Sub
ErrorHandler:
If Err.Number = 5 Or Err.Number = 9 Then
MsgBox “The file could not be found”
ElseIf Err.Number = 1004 Then
MsgBox “There is already a PivotTable at that location”
Else
MsgBox “Error “ & Err & “ - “ & Err.Description
End If
Resume EndOfSub
End Sub
以上方法,創建出壹個4個單元格形狀的數據透視表,透視表中沒有任何字段!