首页 > 解决方案 > 更改 PivotField Excel VBA 上的字体样式

问题描述

我有一个构建我的数据透视表的代码,我想将其中一个字段设置为斜体,但我不知道如何。

我的代码从一开始就是这样的:

With ActiveSheet.PivotTables("Laddsida").PivotFields("Work hrs")
.Orientation = xlDataField
.Position = 6
.Function = xlSum
.NumberFormat = "[h]:mm:ss"
.Name = "Uppskattad arbetad tid"
End With

试过这个:

With ActiveSheet.PivotTables("Laddsida").PivotFields("Work hrs")
.Orientation = xlDataField
.Position = 6
.Function = xlSum
.NumberFormat = "[h]:mm:ss"
.font.Italic = True
.Name = "Uppskattad arbetad tid"
End With

但是得到以下错误:

运行时错误“438”:

对象不支持此属性或方法

在您的帮助下,我设法做到了这一点,但RowRange唯一影响的是第一个,如图所示

在此处输入图像描述

标签: excelvbafontspivot

解决方案


根据我的评论:.Font不是 PivotFields 对象模型已知的属性的一部分。但是,您可以使用PivotField.DataRangewhich 将返回一个Range对象,而该对象又支持.Font; 例如:

Sub Test()

Dim ws as Worksheet: Set ws = ThisWorkbook.Worksheets("????") 'Name of your sheet
ws.PivotTables("Laddsida").PivotFields("Work hrs").DataRange.Font.Italic = True

End Sub

根据您的评论,我认为您的行中有标题,也称为RowRange. 我们可以使用此Range对象来查找您的特定目标标头:

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("????") 'Name of your sheet
Dim cl As Range

Set cl = ws.PivotTables("Laddsida").RowRange.Find("Work hrs")
If Not cl Is Nothing Then
    cl.Font.Italic = True
End If

End Sub

根据您的最新评论,您似乎有多个具有相同值的标头,因此您可能想要使用.FindNext

Sub Test()

Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("????") 'Name of your sheet
Dim cl As Range, rw As Long

With ws.PivotTables("Laddsida").RowRange
    Set cl = .Find("Work hrs")
    If Not cl Is Nothing Then
        rw = cl.Row
        Do
            cl.Font.Italic = True
            Set cl = .FindNext(cl)
        If cl Is Nothing Then GoTo DoneFinding
        Loop While cl.Row <> rw
    End If
DoneFinding:
End With

End Sub

推荐阅读