2012-12-05 42 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