X轴值VBA

时间:2018-04-06 18:22:56

标签: vba excel-vba excel

我目前有以下代码来创建图表。

Private Sub CommandButton3_Click()
    Dim aChart As Chart
    Dim aRange As range


    Set aRange = range(Cells(1, 4), Cells(6, 4))
    Set aChart = Charts.Add
    aChart.HasLegend = False
    aChart.ChartType = xlColumnClustered
    aChart.SetSourceData aRange
    aChart.PlotBy = xlColumns
    aChart.Axes(xlCategory).HasMajorGridlines = True
    aChart.Location xlLocationAsObject, Sheet1.Name
    Sheet1.ChartObjects.Left = 125
    Sheet1.ChartObjects.Top = 250
    Cells(1, 1).Select

End Sub

X轴上显示的值为1,2,3,4,5。但是,我想从工作表中获取我的值。现在有人使用我需要使用的代码从我的工作表中的范围中获取一组值吗?

2 个答案:

答案 0 :(得分:0)

一般语法如下:

Worksheets("Sheet1").ChartObjects("Chart 1").Chart.SeriesCollection(1).XValues = _
"='Sheet1'!$A$1:$D$1"

诸如此类

答案 1 :(得分:0)

尝试下面的代码,代码注释中的解释:

Option Explicit

Private Sub CommandButton3_Click()

    Dim aChart As Chart
    Dim aRange As Range
    Dim axisRange As Range

    Set aRange = Range(Cells(1, 4), Cells(6, 4))

    ' set the x-axis range
    Set axisRange = Range(Cells(1, 3), Cells(6, 3)) '<-- modify this range according to your needs

    Set aChart = Charts.Add
    aChart.HasLegend = False
    aChart.ChartType = xlColumnClustered
    aChart.SetSourceData aRange
    aChart.PlotBy = xlColumns

    ' set the x-axis chart to your created address
    aChart.SeriesCollection(1).XValues = "=" & axisRange.Address(False, False, xlA1, xlExternal)

    aChart.Axes(xlCategory).HasMajorGridlines = True
    aChart.Location xlLocationAsObject, Sheet1.Name
    Sheet1.ChartObjects.Left = 125
    Sheet1.ChartObjects.Top = 250
    Cells(1, 1).Select

End Sub