Excel VBA数据透视表填充标题

在Excel VBA中,我创build了一个数据透视表,并希望用白色字体填充标题(前两行)和底行(一行)蓝色。

下面的代码填充第一个数据集行的内部,而不是头部。

With ActiveSheet.PivotTables(1).TableRange1 .Cells.Borders.LineStyle = xlContinuous .Range("A3:I4").Interior.ColorIndex = 49 .Range("A13:I13").Interior.ColorIndex = 49 End With 

有没有办法来dynamic引用数据透视表的头部和最后一行? 最好是引用“数据透视表标题”,​​而不是报告中的特定范围。

你可以简单地使用这个:

 With ActiveSheet.PivotTables("PivotTable1") Debug.Print "full headers at: " & Intersect(.Parent.Range(.TableRange1.Row & ":" & .DataBodyRange.Row - 1), .TableRange1).Address Debug.Print "last row-range at: " & .TableRange1.Rows(1).Offset(.TableRange1.Rows.Count - 1).Address End With 

但看看你的子,最简单的方法是改变:

 .Range("A3:I4").Interior.ColorIndex = 49 .Range("A13:I13").Interior.ColorIndex = 49 

至:

 Union(.Rows("1:2"), .Rows(.Rows.Count)).Interior.ColorIndex = 49 

有一个dynamic的方式来解决标题行和最后一行:

 Dim pvtFirstRow, pvtLastRow As Integer pvtFirstRow = ActiveSheet.PivotTables(1).TableRange1.row + x ' modify x to the first row where your Pivot data starts pvtLastRow = ActiveSheet.PivotTables(1).TableRange1.Cells(ActiveSheet.PivotTables(1).TableRange1.Cells.count).row 

到目前为止,线程中呈现的代码确实有效,但将来必须重新运行:任何时候主键中的行数​​或列数都会发生变化,您可以坐在没有数据透视的彩色行或列中,在枢轴的错误部分。

我build议你看一下Excel的内置透视样式,select最接近你需要的样式,然后使用这样的代码修改标题行和总行。 没有必要操作单元格的范围,因为下次您可能要closures总行(出于参数的缘故),但是范围仍将被着色。

我logging了一个macros,并删除了所有冗余的代码行,以帮助您查看哪些更改。 我还删除了一个有用的行(.TintAndShade =),并用“ColorIndex =”语句replace它,以强制您似乎更喜欢的蓝色阴影。

运行这个之后,你应该对同一工作簿中的所有其他(现有的和新的)枢轴有相同的样式。 你甚至可以使它默认。 无需再次运行代码,以便在您的数据透视表[刷新]覆盖不同范围的单元格时进行格式化。

您可以从自己的调色板中select另一个样式,并使用您自己的自定义名称作为副本,只要您find并replace下面示例代码中的所有相关string或logging您自己的操作即可:

 Sub ColourPivotStyleForThisBook() 'duplicate blue/medium pivot style from template ActiveWorkbook.TableStyles("PivotStyleMedium2").Duplicate ("PivotStyleMedium2v2" _ ) With ActiveWorkbook.TableStyles("PivotStyleMedium2v2") .ShowAsAvailablePivotTableStyle = True .ShowAsAvailableTableStyle = False .ShowAsAvailableSlicerStyle = False .ShowAsAvailableTimelineStyle = False End With 'now modify header's style (fill) (font colour is white/automatic already) With ActiveWorkbook.TableStyles("PivotStyleMedium2v2").TableStyleElements( _ xlHeaderRow).Interior 'only one/two lines are changing the colours ' .TintAndShade = -0.249977111117893 .ColorIndex = 49 End With 'now modify grand total row's style (fill) (font colour is white/automatic already) With ActiveWorkbook.TableStyles("PivotStyleMedium2v2").TableStyleElements( _ xlTotalRow).Interior 'only one/two lines are changing the colours ' .TintAndShade = -0.249946592608417 .ColorIndex = 49 End With End Sub 

如果得到的结果不是您想要的结果,只需select工作簿中的一部分数据透视表,点击数据透视表工具function区的“devise”选项卡,右键单击代码创build的那个(它应该位于“自定义”顶部的部分),然后单击删除。 希望这可以帮助。

(甚至可以使用类似上面的代码来自定义尚未有数据透视表的其他工作簿中的数据透视表样式。)