VBA中范围内的数据透视图数据标签

时间:2019-01-22 19:14:32

标签: excel vba

Pivot Chart Visual

我正在尝试编辑数据透视图,以便在必要时按比例缩小其数据标签(即6位数字除以1,000),这需要在单元格区域中向数字添加自定义标签以显示它已经缩放。例如,一个最初为800,000的数字将通过自定义公式系列在数据透视表中转换为800,然后另一个包含公式的单元格将确定它是否已缩放并显示“ M”(英里)有。

我可以在不使用VBA的情况下静态地完成此操作,只需在格式化数据标签时选中“值单元格”框中的“来自单元格的值”框即可。但是,更改视图(正如我需要经常做的那样)会重置检查“来自单元格的值”时创建的链接。此外,我的标签经常恢复为未固定且小于我制作的标签。因此,我感觉需要创建一个宏来更新我的数据标签,以包括范围查找和表的每次更改大小。为此,我的代码如下。

Dim numSubs As Integer
Dim Labels As Range
numSubs = 7 'find a way to count number of active series
For i = 1 To numSubs
    With Sheet16.ChartObjects("Chart 2").SeriesCollection(i).DataLabels
        .ShowRange = False
        .Format.TextFrame2.TextRange. _
            InsertChartField msoChartFieldRange, "='New PC Mapping'!$I$32:$I$34", 0 'find a way to cycle thru ranges
        .Format.TextFrame2.TextRange.Font.Bold = msoTrue
        .Format.TextFrame2.TextRange.Font.Size = 14
    End With
Next

首先,VBA告诉我无法在图表上运行SeriesCollection,这是我已阅读的所有示例中显示的方法。我不知道这里的症结所在。我已经验证它可以识别Sheet16.ChartObjects(“ Chart 2”)

第二,我需要找到一种在多个范围内循环的方法,因为每个系列都有其自己的范围。我在这里的代码行来自记录宏,因为我无法在任何地方在线找到用于执行此操作的代码,因此我敢肯定它可以改进,但是在当前形式下,它采用了一系列的公式,这使它很难例如,以Range.Offset移动。

从那里,我知道在处理数据透视表时如何触发它。我只需要一些帮助就可以在一个系列中使用它,我可以从那里进行概括。谢谢!

1 个答案:

答案 0 :(得分:0)

谢谢克里斯(Chris)的帮助!

我发现了一种执行所需循环的方法:

Set dataLabelRange = Sheet24.Range("I20:I22").Offset(0, i)
dataLabelString = "='New PC Mapping'!" & dataLabelRange.Address

使用i ++,每个循环和dataLabelString插入到地址上方的位置。

对于需要一种方法来重新链接宏中地址的任何人,例如通过点击可能会切断这些链接的数据透视表触发,我的最终代码如下:

Dim dataLabelRange As Range
Dim dataLabelString As String
Dim mySeries As Series
Dim i As Integer
i = 0
For Each mySeries In Sheet16.ChartObjects("Chart 1").Chart.FullSeriesCollection
    Set dataLabelRange = Sheet24.Range("I20:I22").Offset(0, i) 'runs through columns of 3 side by side, which is how I had the labels I wanted to add
    dataLabelString = "='*Sheet Name*'!" & dataLabelRange.Address
    mySeries.ApplyDataLabels
    With mySeries.DataLabels
        .ShowRange = False
        .Format.TextFrame2.TextRange.InsertChartField msoChartFieldRange, dataLabelString, 0
        .ShowRange = True
        .Format.TextFrame2.TextRange.Font.Bold = msoTrue 'addition code for formatting labels
        .Format.TextFrame2.TextRange.Font.Size = 14
        .Separator = " "
    End With
    i = i + 1
Next mySeries