excel 使用pivot创建透视图

00jrzges  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(174)

我写了下面的代码从我的数据透视表创建一个数据透视图
代码运行正常,但是当它到达.ApplyDataLabels行时,会导致运行时438错误消息
当我点击“结束”时,仍然会创建图表,但不会出现数据标签:

Sub Graph_Test_3()

Dim chtObj As ChartObject
Dim PvtSht As Worksheet
Dim PvtTbl As PivotTable
Dim ser As Series

'set the Pivot sheet
Set PvtSht = Worksheets("Pivots And Graphs")

' set the Pivot Table object
Set PvtTbl = PvtSht.PivotTables("PivotTable5")

' set the Chart Object
Set chtObj = PvtSht.ChartObjects.Add(300, 200, 550, 200)

' modify ChartObject properties
With chtObj
    .Chart.SetSourceData PvtTbl.TableRange2 'set the chart’s data range to the Pivot-Table’s TableRange2
    .Chart.ChartType = xlColumnStacked
    .Name = "Performance Spread 24" 'change the name of the chart
    .Chart.HasTitle = True 'add a chart title
    .Chart.ChartTitle.Text = "Performance Spread 24" 'set the chart title text
    .Chart.Axes(xlCategory).HasTitle = True 'add an x-axis title
    .Chart.Axes(xlCategory).AxisTitle.Text = "Performance Range" 'set the x-axis title text
    .Chart.Axes(xlValue).HasTitle = True 'add a y-axis title
    .Chart.Axes(xlValue).AxisTitle.Text = "Headcount" 'set the y-axis title text
    .Chart.Axes(xlCategory).MajorGridlines.Delete 'remove the x-axis gridlines
    .Chart.Axes(xlValue).MajorGridlines.Delete 'remove the y-axis gridlines
    For Each ser In .Chart.SeriesCollection
       .ApplyDataLabels xlDataLabelsShowValue
        With ser.DataLabels
            .Position = xlLabelPositionOutsideEnd
            .Font.Size = 12
            .Font.Colour = vbBlack
            'loop through each series in the chart ser
            'position the data labels outside end Next ser End With
        End With
    Next ser
End With
End Sub

字符串
我尝试将行.ApplyDataLabels xlDataLabelsShowValue更改为.ApplyDataLabels.Type = xlDataLabelsShowValue,但这给出了相同的错误消息和相同的结果
抱歉,如果这是基本的,我是相当新的电子邮件!

jchrr9hc

jchrr9hc1#

以下变化对我来说很有用:

  • For Each循环更改为常规For循环,并索引到.SeriesCollection

1.删除.Position = xlLabelPositionOutsideEnd或更改为有效位置。xlLabelPositionOutsideEnd对于堆叠柱形图无效。可用选项包括:

  1. xlLabelPositionCenter
  2. xlLabelPositionInsideEnd
  3. xlLabelPositionInsideBase
    1.将.Colour更改为.Color
.Chart.Axes(xlValue).MajorGridlines.Delete 'remove the y-axis gridlines
    
    Dim i As Long
    For i = 1 To .Chart.SeriesCollection.Count
        Set ser = .Chart.SeriesCollection(i)
        ser.ApplyDataLabels
        
        With ser.DataLabels
            .Position = xlLabelPositionCenter
            .Font.Size = 12
            .Font.Color = vbBlack
        End With
    Next

字符串

相关问题