【问题标题】:Add Variable Series to Chart w/ VBA使用 VBA 将变量系列添加到图表
【发布时间】:2013-03-06 20:19:16
【问题描述】:

我有一个如下所示的电子表格:

A     1/1/2013     100
A     2/1/2013     200
A     3/1/2013     300
B     1/1/2013     150
B     2/1/2013     175
B     3/1/2013     200

三列是固定的,但每个系列(第一列)的条目数会有所不同。

使用 VBA,我想自动将第一列中的每个唯一值作为一个系列添加到散点图上,第二列用于 X 值,第三列用于 Y 值。例如,对于上面的 A 系列,我需要动态确定范围 B1:B3 和 C1:C3。

我使用录制的宏生成了将系列添加到图表的代码,所以我真正的障碍是找到每个系列的范围。我需要保留系列的名称以进行关联(第一列),并且希望避免使用过滤器。

【问题讨论】:

标签: excel vba charts series


【解决方案1】:

我最终想到了一种有点迂回的解决方法;这是任何有兴趣的人的代码,适合我原始问题的布局:

Sub Example()
    ' Variable Definitions
    Dim y As Integer
    Dim Name(73) As String
    Dim Mins(73) As Integer
    Dim Maxs(73) As Integer

    ' Loop Through Name Column (Series)
    For Each x In Range("A4:A" & Cells(Rows.Count, "A").End(xlUp).Row)

        ' Add Values to Arrays, If Not Preexisting
        If IsInArray(x.Value(), Name) = False Then
            Name(y) = x.Value()
            Mins(y) = x.Row()
            Maxs(y) = x.Row()
            y = y + 1
        Else
            Maxs(y - 1) = x.Row()
        End If

    Next x

    ' Add to Chart
    ActiveSheet.ChartObjects("Chart 1").Activate
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.FullSeriesCollection(1).Name = Name(0)
    ActiveChart.FullSeriesCollection(1).XValues = "=Data!$B$" & Mins(0) & ":$B$" & Maxs(0)
    ActiveChart.FullSeriesCollection(1).Values = "=Data!$C$" & Mins(0) & ":$C$" & Maxs(0)
End Sub

' Array Function from @JimmyPena
' http://stackoverflow.com/a/11112305/2141501
Function IsInArray(stringToBeFound As String, arr As Variant) As Boolean
  IsInArray = (UBound(Filter(arr, stringToBeFound)) > -1)
End Function

【讨论】:

  • 当心Filter - 如果您曾经有一个系列名称是另一个名称的子字符串,那么如果较长的名称已添加到您的数组中,您将得到错误的命中。
猜你喜欢
  • 1970-01-01
  • 2015-06-03
  • 2021-06-05
  • 2012-09-21
  • 2017-12-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 2014-07-17
相关资源
最近更新 更多