我有两张纸。 Sheet1"结果"它有一个包含8列的表。
我有第二张" Sum"我在哪里为Reuslt表生成数据透视表。
代码工作正常,但它会计算每列的总和并给出结果。
我想仅为最后更新的行设置数据透视表。
每次和每周最后一次更新行都会更改。下周,更新将在17日发现,依此类推......
有人能建议我怎么做吗?任何领导都会有所帮助
Sub sum2017()
Dim ws9 As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Set ws9 = Sheets("Sum")
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, "'Result'!R1C1:R1048576C6")
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
pt9.AddDataField pt9.PivotFields("NOK"), "Sum of NOK", xlSum
pt9.AddDataField pt9.PivotFields("OK"), "Sum of OK", xlSum
pt9.AddDataField pt9.PivotFields("Total"), "Sum of Total", xlSum
pt9.AddDataField pt9.PivotFields("NOK %"), "Sum of NOK %", xlSum
pt9.AddDataField pt9.PivotFields("OK %"), "Sum of OK %", xlSum
pt9.DataLabelRange.HorizontalAlignment = xlCenter
pt9.DataLabelRange.ReadingOrder = xlContext
pt9.TableRange2.HorizontalAlignment = xlCenter
End Sub
答案 0 :(得分:1)
此代码有效,但每次创建新的pivottable时都会添加帮助表。如果您不想这样做,只需添加一些额外的工作表,根据需要命名,而不是将wskHelpSheet的引用更改为该工作表,并记住始终在宏的开头清理此工作表。我希望你听起来很清楚:)
Sub sum2017()
Dim ws9 As Worksheet
Dim wskResult As Worksheet
Dim pc9 As PivotCache
Dim pt9 As PivotTable
Dim ct9 As Integer
Dim rngPivotRangeHeaders As Range
Dim lngLRow As Long
Dim lngLCol As Long
Dim rngPivotRangeRecords As Range
Dim rngPTRange As Range
Dim wskHelpSheet As Worksheet
Set ws9 = Sheets("Sum")
Set wskResult = ThisWorkbook.Sheets("Result")
Set wskHelpSheet = Worksheets.Add
With wskResult
lngLRow = .Cells(Rows.Count, "B").End(xlUp).Row
lngLCol = .Cells(1, Columns.Count).End(xlToLeft).Column
Set rngPivotRangeHeaders = .Range(.Cells(1, 1), .Cells(1, lngLCol))
Set rngPivotRangeRecords = .Range(.Cells(lngLRow, 1), .Cells(lngLRow, lngLCol))
Set rngPTRange = Union(rngPivotRangeHeaders, rngPivotRangeRecords)
rngPTRange.Copy
End With
With wskHelpSheet
.Range("a1").PasteSpecial Paste:=xlPasteValues
lngLRow = .Cells(Rows.Count, "B").End(xlUp).Row
lngLCol = .Cells(1, Columns.Count).End(xlToLeft).Column
Set rngPTRange = .Range(.Cells(1, 1), .Cells(lngLRow, lngLCol))
End With
Set pc9 = ActiveWorkbook.PivotCaches.Create(xlDatabase, rngPTRange)
Set pt9 = pc9.CreatePivotTable(ws9.Range("A3"))
With pt9
.AddDataField .PivotFields("NOK"), "Sum of NOK", xlSum
.AddDataField .PivotFields("OK"), "Sum of OK", xlSum
.AddDataField .PivotFields("Total"), "Sum of Total", xlSum
.AddDataField .PivotFields("NOK %"), "Sum of NOK %", xlSum
.AddDataField .PivotFields("OK %"), "Sum of OK %", xlSum
.DataLabelRange.HorizontalAlignment = xlCenter
.DataLabelRange.ReadingOrder = xlContext
.TableRange2.HorizontalAlignment = xlCenter
End With
End Sub