vba excel编辑/添加系列和水平轴标签

时间:2017-06-30 19:01:17

标签: excel vba excel-vba

我的当前代码在x轴的每个部分放置三个条形图。我希望有三个单独的部分,每个部分都有自己的条形图。 enter image description here这是我当前的代码

Sub DrawChart1()
 Dim i As Long
 Dim j As Long
 Dim ws As Worksheet
 Dim rCht As Range, rYVals As Range
 Dim cht As Chart

 ' finding the number of rows
 Set ws = Worksheets("sheet1")
 'j = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row


 'j = ws.Cells(9, 1).Row
 j = ws.Range(ws.Cells(1, 1), ws.Cells(1, 3)).Row
 ' start with X values (row 10 to j), include header row (row 9)
 Set rCht = ws.Range(ws.Cells(9, 1), ws.Cells(j, 1))

 Set rCht = ws.Range(ws.Cells(1, 1), ws.Cells(1, 3))

 ' add column of Y values if row 8 of column is TRUE
' For i = 2 To 14
  For i = 1 To 3
  If ws.Cells(8, 1).Value Then
  Set rYVals = ws.Range(ws.Cells(9, i), ws.Cells(9, i))
   '     Set rYVals = ws.Range(ws.Cells(9, 2), ws.Cells(9, 2))

     Set rCht = Union(rCht, rYVals)
   End If
 Next

   ' if we've had any Y values, insert chart, using range we've built up
    If Not rYVals Is Nothing Then
     Set cht = ws.Shapes.AddChart(xlColumn).Chart
    cht.SetSourceData Source:=rCht, PlotBy:=xlColumns
    End If
   End Sub

1 个答案:

答案 0 :(得分:0)

我认为编辑/添加系列和水平轴标签是不可能的。 而是编辑轴标签,可以编辑seriescollection point的标签。

Sub DrawChart1()
 Dim i As Long
 Dim j As Long
 Dim ws As Worksheet
 Dim rCht As Range, rYVals As Range
 Dim cht As Chart
 Dim n As Integer
    Set ws = Worksheets("sheet1")

    Set cht = ws.Shapes.AddChart(xlColumn).Chart
    With cht
        For i = 1 To 3
            If ws.Cells(8, 1).Value Then
                n = n + 1
                .SeriesCollection.NewSeries
                With .SeriesCollection(n)
                    .Name = ws.Cells(1, i).Text
                    .XValues = n
                    .Values = ws.Cells(9, i)
                    With .Points(1)
                        .ApplyDataLabels
                        .DataLabel.Text = ws.Cells(1, i).Text
                    End With
                End With
            End If
        Next i
        .ChartGroups(1).Overlap = -100
    End With

End Sub