X轴未正确绘制图表

时间:2013-02-20 20:18:31

标签: excel excel-vba charts axis vba

我有一个为我绘制数据图表的宏。关于宏的一切工作有1个例外:我想重新指定x轴标签。宏确实这样做但它做得不对。在某些情况下,它会移动类别,而在其他情况下,它会将类别标记为完全错误。该宏应该按产品ID(每个产品ID一个图表)绘制数据,然后将x轴类别更改为“图表数据”中F列中的标签。

提前感谢您的帮助。

下面是创建图表并随后更改x轴的宏的一部分:

Sub MakeCharts()
Dim sh As Worksheet
Dim rAllData As Range
Dim rChartData As Range
Dim cl As Range
Dim rwStart As Long, rwCnt As Long
Dim chrt As Chart

Set sh = ActiveSheet
ActiveSheet.Range("a1").Select
With sh

' Get reference to all data
    Set rAllData = .Range(.[A2], .[A2].End(xlDown)).Resize(, 5)
    ' Get reference to first cell in data range
    rwStart = 1
    Set cl = rAllData.Cells(rwStart, 1)
    Do While cl <> ""
        ' cl points to first cell in a station data set
        ' Count rows in current data set
        rwCnt = Application.WorksheetFunction. _
           CountIfs(rAllData.Columns(1), cl.Value)
        ' Get reference to current data set range
        Set rChartData = rAllData.Cells(rwStart, 1).Resize(rwCnt, 5)
        ' Create Chart next to data set
        Set chrt = .Shapes.AddChart(xlLineMarkers, _
           rChartData.Width, .Range(.[A2], cl).Height).Chart
        With chrt
            .SetSourceData Source:=rChartData.Offset(0, 1).Resize(, 4)
            ' -----> Set any chart properties here <-----

            ' Add Title
            .SetElement msoElementChartTitleCenteredOverlay
            .ChartTitle.Caption = cl.Value

            'Change chart name
            .Parent.Name = cl.Value

            'Remove Legend
            .SetElement (msoElementLegendNone)

            ' Adjust plot size to allow for title
            .PlotArea.Height = .PlotArea.Height - .ChartTitle.Height
            .PlotArea.Top = .PlotArea.Top + .ChartTitle.Height

            'Change the x-axis to a more organized set
            .SeriesCollection(1).XValues = "='Chart Data'!$F$2:$F$1048576"

            'Set Max and Min for charts
            .Axes(xlValue).MinimumScale = Sheets("Chart Data").Range("K1")
            .Axes(xlValue).MaximumScale = Sheets("Chart Data").Range("K2")

            'Adjust x-axis to tilt 45 degrees top left to bottom right
            .Axes(xlCategory).TickLabels.Orientation = 45



        End With


        ' Get next data set
        rwStart = rwStart + rwCnt
        Set cl = rAllData.Cells(rwStart, 1)
    Loop

End With

1 个答案:

答案 0 :(得分:0)

在'将x轴更改为更有组织的集合下,我使用了以下代码:

.SeriesCollection(1).XValues = "='Chart Data'!" & rChartData.Offset(, 5).Resize(, 1).Address