1

我要做的是创建一个 2d 堆叠图表,其中我的系列的位置意味着它们在队列中的位置(位置 1 - 作为堆叠列的最上面的部分是最后得到服务的,位置 2 - 是堆叠柱的底部将首先向上)。

我已将数据格式化为如下所示(但如果解决方案需要,可以轻松更改):

Task 1   Task 2   Task 3   <- x-axis  
A  100   B 400    B 510    <- This row is position 1      
B  200   A 200    A 300    <- This row is position 2   
^-Legend

我遇到的问题是,我希望所有任务都在同一个图表上,而 Excel 并没有在每个 x 处识别 A 和 B 的位置。它只是从第 1 列假设第 2 行是 A,第 3 行是 B 和不会根据 A/B 键在每个后续列中进行调整。我想知道是否有办法做到这一点。

回顾一下,是否可以获得具有多个 x 值的 2d 堆叠图表,以识别每个唯一 x 值处的图例键的位置(无论它应该在列的顶部还是底部)。任何解决方案,无论是 VBA 还是表格内公式,我都没有运气。提前致谢。

4

1 回答 1

2
'Run this macro from the sheet containing your data, after highlightling the data.
Sub Macro3()

  'The below code assumes that you have already selected
  'the columns containing your data and that the first column,
  'and every 2nd column after that contains your legend keys.
  Dim rng As Range
  Set rng = Selection

  Dim colNum As Integer
  Dim rowNum As Integer
  Dim strLegend As String
  Dim rowStart As Integer
  Dim colStart As Integer
  Dim strSeries As String
  Dim i As Integer
  Dim seriesNum As Integer
  Dim shtName As String

  rowStart = rng.Row
  colStart = rng.Column
  shtName = ActiveSheet.Name & "!"

  'Creates an empty chart...
  ActiveSheet.Shapes.AddChart.Select
  '...of type StackedColumn.
  ActiveChart.ChartType = xlColumnStacked

  seriesNum = 0
  'Select all the cells that match the legend in the first column.
  For rowNum = 0 To rng.Rows.Count - 1
    strLegend = Cells(rowStart + rowNum, colStart).Value
    strSeries = "=" & shtName & Cells(rowStart + rowNum, colStart + 1).Address
    For colNum = 2 To rng.Columns.Count - 1 Step 2
        For i = 0 To rng.Rows.Count - 1
            If Cells(rowStart + i, colStart + colNum).Value = strLegend Then
                strSeries = strSeries & "," & shtName & Cells(rowStart + i, colStart + colNum + 1).Address
                Exit For
            End If
        Next
    Next
    'Create a new series.
    ActiveChart.SeriesCollection.NewSeries
    seriesNum = seriesNum + 1
    'Set the legend.
    ActiveChart.SeriesCollection(seriesNum).Name = strLegend
    'Set the X axis labels to nothing, so the default is used.
    ActiveChart.SeriesCollection(seriesNum).XValues = ""
    'Set the series data.
    ActiveChart.SeriesCollection(seriesNum).Values = strSeries
  Next
  'An extra series gets added automatically???
  'This code removes it.
  If ActiveChart.SeriesCollection.Count > rng.Rows.Count Then
    ActiveChart.SeriesCollection(rng.Rows.Count + 1).Delete
  End If
End Sub

此代码要求您的图例值和数值分别位于单独的列中,如下所示。此示例中未使用标签“任务 1”等。

A | 100 | B | 400 | B | 510 
B | 200 | A | 200 | A | 300
于 2012-07-12T17:50:41.307 回答