Excel VBA - 图表格式化轴标签

时间:2016-06-08 19:50:38

标签: excel vba excel-vba macros

我正在尝试将轴标签添加到我的图表中。以下是我的代码的一部分。

首先,我的代码在运行添加主轴标题的行时不会产生错误。尽管没有注册错误,我的图表仍然没有轴标题的文本框。

其次,当我尝试添加辅助轴标题时,我不确定为什么我的代码会产生错误。我从宏录制器中复制了这部分代码,所以我很确定语法是正确的。

感谢您的帮助!

Dim myChart As Chart, cht As ChartObject
Dim rngChart As Range, destSht As String
Dim rngData As Range

destSht = ActiveSheet.Name
Set myChart = Charts.Add
Set myChart = myChart.Location(where:=xlLocationAsObject, Name:=destSht)

With ActiveSheet.ListObjects("Table1").DataBodyRange
Set rngData = Union(.Columns(2), .Columns(9), .Columns(10), .Columns(11), .Columns(12))
End With

With myChart
.SetSourceData Source:=rngData, PlotBy:=xlColumns
.ChartType = xlColumnClustered
.ChartStyle = 209
.FullSeriesCollection(1).Name = "AHT"
.SetElement (msoElementChartTitleAboveChart)
    .ChartTitle.Text = "AHT/Transfer Metrics"

'*****PROBLEM SECTION*****
.SetElement (msoElementPrimaryValueAxisTitleAdjacentToAxis)
'*****Below is the line of code that is giving me an error*****
.SetElement (msoElementSecondaryValueAxisTitleAdjacentToAxis)
'******              *****

With .FullSeriesCollection(2)
    .Name = "Target AHT"
    .ChartType = xlLine
    .AxisGroup = 1
    .Select
        With Selection.Format.Line
            .Weight = 1
        End With
End With
With .FullSeriesCollection(3)
    .ChartType = xlLineMarkers
    .AxisGroup = 2
    .Name = "Transfers"
    .Select
        With Selection.Format.Line
            .Weight = 1.75
        End With
End With
With .FullSeriesCollection(4)
    .ChartType = xlLine
    .AxisGroup = 2
    .Name = "Target Transfers"
    .Select
        With Selection.Format.Line
            .Weight = 1
        End With
End With
End With

2 个答案:

答案 0 :(得分:2)

    With .Axes(xlValue, xlPrimary)
        .HasTitle = True
        .AxisTitle.Text = "AHT (s)"
    End With

答案 1 :(得分:1)

我认为这是因为你还没有创建辅助轴。在格式化所有系列

之后尝试放置这两行