2012-12-05 44 views
1

我正在處理一個宏,我將數據透視表放在一起。我的問題: 我不能讓計算部分工作。每當我在PivotField(18)應該計算.Function = xlCount的階段運行代碼時,我得到一個錯誤。我得到的錯誤是「範圍級失敗的1004選擇方法」。數據透視表格式化返回錯誤

我在網上找到的所有例子和MS幫助部分都是我設置我的代碼的結構。我錯過了什麼?

任何幫助,高度讚賞...

我一直工作在這一天的大部分時間。以下頁面(Link)一直非常有幫助,但並沒有幫助我解決這個特殊問題。

' Start of PivotSpecific Formatting 
Set pt = ActiveSheet.PivotTables("PT" & wsNewWorksheetName) 
With pt 
    ' Prevent AutoFormatting of Columns 
    .HasAutoFormat = False 
    ' Hide Field Headers 
    .DisplayFieldCaptions = False 
    .TableStyle2 = "PivotStyleMedium2" 
    ' Apply calculation to numbers and change Caption 
    With .PivotFields(18) 
     .Caption = "Demand" 
     .Function = xlCount 
     .NumberFormat = "#,##0" 
    End With 
    With .PivotFields(15) 
     .Caption = "Lowest OP" 
     .Function = xlMin 
     .NumberFormat = "#,##0.00" 
    End With 
End With 

更新1:透視表的截圖 Pivot Table Screenshot

更新2:從bonCodigo 測試的代碼下面是調整到我的工作簿中的代碼。有了這個,我得到上線運行時錯誤91: 設置pvField = pvTable.PivotFields(18)

Dim wkSheet As Worksheet 
Dim pvTable As PivotTable 
Dim pvField As PivotField 

Set wkSheet = ThisWorkbook.Worksheets(wsNewWorksheetName) 
Set pvTble = wkSheet.PivotTables("PT" & wsNewWorksheetName) 
Set pvField = pvTable.PivotFields(18) 

With pvField 
    .Caption = "Demand" 
    .Function = xlCount 
    .orientation = xlDataField 
    .NumberFormat = "#,##0" 
End With 

Set pvField = Nothing 
Set pvTable = Nothing 
Set wkSheet = Nothing 
+0

你能告訴我們你的數據透視表是怎麼樣的嗎?你希望通過這段代碼得到什麼結果?你是否只在'.Function = xlCount'中出錯? '.function = xlMin'怎麼樣?你的'.PivotFields(18)'的名字是什麼?你確定它是「數」嗎?還是像'sum'一樣的東西? – bonCodigo

+0

@bonCodigo我在代碼中的.Function =中都找到了它。我會上傳表格的截圖。 – rohrl77

+0

@bonCodigo PivotFields(18)的名稱是「Nachfrage」...但是,我不想使用該名稱,因爲該應用程序將在各種計算機上使用,並非所有計算機都具有相同的語言設置。這意味着「Anzahl von」(英文中的「Count of」)在運行宏時可能會導致問題。 – rohrl77

回答

1

試試這個,請與你的結果發表評論。所以我們可以從那裏看到。

Option Explicit 

'-- whatever other code you may have... 

Dim wkSheet as Worksheet 
Dim pvTable as PivotTable 
Dim pvField as PivotField 

Set wkSheet = ThisWorkbook.Worksheets("Sheet1") '-- user proper sheet name explicitly 
Set pvTble = wkSheet.PivotTables("PivotTable1") 
    ' or wkSheet.PivotTables(1) '-- use pivot table name or index 
Set pvField = pvTable.PivotFields("SomeField") '-- use pivot field name or index 

' -- do whatever you want to do with the pivot table 

' -- do what you need to do with the pivot field 
With pvField 
    .Caption = "Demand" 
    .Orientation = xlDataField '--<< THIS could well be the culprit 
    .Function = xlCount 
    .NumberFormat = "#,##0" 
End With 

Set pvField = Nothing 
Set PvTable = Nothing 
Set wkSheet = Nothing 

既然你有多個字段的格式,我建議你使用一個循環,如果他們是連續使用DataFields Index

例如pvTable.DataFields(1).Function = xlCount

否則,您將不得不單獨定義它們。最好將變量指定爲您想要交互的對象的引用。 :)

+0

謝謝。請參閱上面的更新2! – rohrl77

+0

更新爲'orientation',請進行測試。 – bonCodigo

+0

我插入'.orientation',但它實際上停止之前,它甚至到達那裏......我得到了運行時錯誤上'Set pvField = pvTable.PivotFields(18)' – rohrl77