Excel 2010 VBA .. 向现有图表添加系列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14897672/
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-11 19:38:04  来源:igfitidea点击:

Excel 2010 VBA.. Adding series to existing chart

excel-vbavbaexcel

提问by kevin king

I am currently trying to populate a chart with data where the user can simply press the button on the spreadsheet. The issue I am having is I need the button to copy data to a data sheet and then the chart will populate from the data sheet. I can do this, but I need a new series created on the chart for every new data that is ente

我目前正在尝试用数据填充图表,用户只需按下电子表格上的按钮即可。我遇到的问题是我需要按钮将数据复制到数据表,然后图表将从数据表中填充。我可以做到这一点,但我需要在图表上为输入的每个新数据创建一个新系列

Sub RoundedRectangle2_Click()

End Sub


Sub MAPS()
Sheets("MAPS_FORM").Range("e47").Copy
Sheets("Data_Sheet").Range("b65536").End(xlUp).Offset(1, 0).PasteSpecial _
Paste:=xlPasteValues
Application.CutCopyMode = False
Sheets("MAPS_FORM").Range("d2").Copy
Sheets("Data_Sheet").Range("a65536").End(xlUp).Offset(1, 0).PasteSpecial _
Paste:=xlPasteValues
Application.CutCopyMode = False



Sheets("Data_Sheet").Range("b2:b46").Copy
Charts("Chart1").SeriesCollection.Paste

Range("e6:i8").ClearContents
Range("e12:i19").ClearContents
Range("e23:i27").ClearContents
Range("e31:i36").ClearContents
Range("e40:i43").ClearContents
Range("d2").ClearContents
Sheets("Data_Sheet").Select
End Sub

回答by Siddharth Rout

Simply change the .SetSourceDataproperty after you add the data.

.SetSourceData添加数据后只需更改属性即可。

Let's take an example

让我们举个例子

Lets say you data is from A1:A5and the chart is based on that range. See screenshot below

假设您的数据来自A1:A5并且图表基于该范围。看下面的截图

enter image description here

在此处输入图片说明

Now lets say your added data is from B1:B5and want that to show as a series in the chart then simply use this code

现在假设您添加的数据来自B1:B5并希望将其显示为图表中的系列然后只需使用此代码

Option Explicit

'~~> Please amend the code as applicable
Sub Sample()
    Dim objChrt As ChartObject
    Dim chrt As Chart

    Set objChrt = ActiveSheet.ChartObjects("Chart 1")
    Set chrt = objChrt.Chart

    With chrt
        .SetSourceData (ActiveSheet.Range("A1:B5"))
    End With
End Sub

When you run the code the chart will automatically show the new series.

当您运行代码时,图表将自动显示新系列。

enter image description here

在此处输入图片说明