VBA:使用 VBA 从 Excel 图表中编辑图例名称

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41366120/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-12 11:46:13  来源:igfitidea点击:

VBA: Edit legend names from excel chart using VBA

excelvbaexcel-vba

提问by Alejandro Jiménez Rico

I have made a chart where I try to plot some specific data. For that purpose I made this code:

我制作了一个图表,我尝试绘制一些特定的数据。为此,我编写了以下代码:

Sub plotsim()
Dim sh As Worksheet
Dim chrt As Chart
worksh = Application.Sheets.Count
Set sh = ActiveWorkbook.Worksheets("Simulation")
Set chrt = sh.Shapes.AddChart.Chart
With chrt
    .ChartType = xlLine
    .SeriesCollection.NewSeries
    .SeriesCollection(1).Name = "=""Portfolio forecast"""
    .SeriesCollection(1).XValues = Sheets("Simulation").Range("A2:A" & fsize + 1)
    .SeriesCollection(1).Values = Sheets("Simulation").Range(Sheets("Simulation").Cells(2, worksh + 1), Sheets("Simulation").Cells(fsize + 1, worksh + 1))
End With
End Sub

But once I take a look at the chart, what I see is a legend with two different lines.

但是一旦我查看图表,我看到的是带有两条不同线条的图例。

How can I remove (or edit) the Series2title?

如何删除(或编辑)Series2标题?

回答by Porcupine911

If you really wanted to edit Series2in the legend you would change it the same manner you changed the name of Series1:

如果您真的想在图例中编辑Series2,您可以像更改 Series1 的名称一样更改它:

.SeriesCollection(2).Name = "Unwanted series"

enter image description here

在此处输入图片说明



Note: I had originally answered with the following:

注意:我最初回答如下:

The following line of code is adding your unwanted Series2:

.SeriesCollection.NewSeries

Simply remove it.

以下代码行添加了您不需要的Series2

.SeriesCollection.NewSeries

只需将其删除。

But I see now that it was not entirely correct. Sometimes an additional one is created, sometimes not, depending on what has happened in the past on the sheet (I think I'm missing something obvious). I've been able to reproduce both behaviors. If you somehow end up with additional series', you could remove any superfluous ones with a call to:

但我现在看到它并不完全正确。有时会创建一个额外的,有时不会,这取决于过去在工作表上发生的事情(我想我遗漏了一些明显的东西)。我已经能够重现这两种行为。如果你以某种方式结束了额外的系列',你可以通过调用以下方法删除任何多余的:

.SeriesCollection(2).Delete

so long as you use the correct series number. You could include a test like this to see if an extra one has been made:

只要您使用正确的序列号。您可以包括这样的测试,以查看是否进行了额外的测试:

If .SeriesCollection.Count > 1 then .SeriesCollection(2).Delete