简体   繁体   English

如何在VBA中对图表图例进行排序

[英]How to sort Legend of a chart in VBA

I was trying to sort my legend and could not find any reliable answer. 我试图对图例进行排序,但找不到任何可靠的答案。 Here, Reordering Chart Data Series in Excel , you can find out how to do it manually. 在这里,您可以在Excel中对图表数据系列进行重新排序 ,以了解如何手动进行。 Also, a code was posted there, which was not working for me and it was too complicated for a task like this. 另外,在那里发布了一个代码,它对我不起作用,对于这样的任务来说太复杂了。 Basically, we are trying to automate what is shown in the following picture. 基本上,我们试图使下图所示的过程自动化。

在此处输入图片说明

Please propose your solutions or look-up my answer if you have the same problem. 如果您有相同的问题,请提出解决方案或查询我的答案。

This code gets the series names, put them into an array, sort the array and based on that defines the plotting order which will give the desired output. 此代码获取序列名称,将其放入数组中,对数组进行排序,然后根据该序列定义打印顺序,以给出所需的输出。 You can change ActiveChart to chart name to be more explicit. 您可以将ActiveChart更改为图表名称,以使其更明确。 Feel free to apply any improvement. 随时进行任何改进。

Sub Sorting_Legend()


    Dim Arr()
    ReDim Arr(1 To ActiveChart.FullSeriesCollection.Count)

        'Assigning Series names to an array
        For i = LBound(Arr) To UBound(Arr)
        Arr(i) = ActiveChart.FullSeriesCollection(i).Name
        Next i

        'Bubble-Sort (Sort the array in increasing order)
        For r1 = LBound(Arr) To UBound(Arr)
            rval = Arr(r1)
                For r2 = LBound(Arr) To UBound(Arr)
                    If Arr(r2) > rval Then 'Change ">" to "<" to make it decreasing
                        Arr(r1) = Arr(r2)
                        Arr(r2) = rval
                        rval = Arr(r1)
                    End If
                Next r2
        Next r1

    'Defining the PlotOrder
    For i = LBound(Arr) To UBound(Arr)
    ActiveChart.FullSeriesCollection(Arr(i)).PlotOrder = i
    Next i

End Sub

Excel treats name of the series as text. Excel将系列名称视为文本。 So you would encounter the problem that instead of having 1,2,3,... you end up getting 1,10,11,...,19,2,20,... . 因此,您将遇到一个问题,而不是拥有1,2,3,...最终得到1,10,11,...,19,2,20,... In that case, convert the array to number. 在这种情况下,请将数组转换为数字。 There are questions here, like convert an array to number , that would do the job. 这里有一些问题,例如将数组转换为number ,就可以完成工作。 You can also simply compare Cdbl of each element with the one of the other. 您还可以简单地将每个元素的Cdbl与另一个元素进行比较。 (ie If Cdbl(Arr(r2)) > Cdbl(rval) Then ... ) (即If Cdbl(Arr(r2)) > Cdbl(rval) Then ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM