插入图表并使用来自不同工作表的数据

我试图插入一个工作表,将显示来自4列的信息的图表。

x轴有date,y轴有$数量。 这是我从录制一个macros(它显示了我至less想要的)得到的:

ActiveSheet.Shapes.AddChart.Select ActiveChart.ChartType = xlXYScatterSmoothNoMarkers ActiveChart.ChartArea.Select ActiveChart.SeriesCollection.NewSeries ActiveChart.SeriesCollection(1).Name = "=""target""" ActiveChart.SeriesCollection(1).XValues = "=MacroParty!$R$4:$R$55" ActiveChart.SeriesCollection(1).Values = "=MacroParty!$S$4:$S$55" ActiveChart.SeriesCollection.NewSeries ActiveChart.SeriesCollection(2).Name = "=""current""" ActiveChart.SeriesCollection(2).XValues = "=VA05NDump!$G$2:$G$833" ActiveChart.SeriesCollection(2).Values = "=VA05NDump!$P$2:$P$833" 

问题是,这只是一张图表中间的工作表,我正在寻找它在一个特定的位置。

我猜测有这样一个更好的方式来写这个,但我是新来的VBA和依靠蛮力的方法。

任何帮助将不胜感激!

好的,你可以清理一下。 macroslogging器是伟大的,因为它可以帮助你看到你需要做什么,但它只是简单地复制键击或鼠标点击,并且在VBA编程的点应该是直接与对象 – 比模仿击键更有效

我将展示一些使用variables的例子,使你的代码更简洁,希望更容易解释。 我会为你评论,这样你就可以看到我在做什么,为什么。

 Sub Test() Dim cObj As Shape 'A Shape container for the Chart Dim cht As Chart 'Variable will represent the chart Dim srs As Series 'Variable will represent series Set cObj = ActiveSheet.Shapes.AddChart '##cObj will refer to this shape Set cht = cObj.Chart '## cht will refer to this chart '(Now, the variable "cht" will refer to this specific chart until/unless ' you assign it to another chart. '## Set the chart type: cht.ChartType = xlXYScatterSmoothNoMarkers '## To manipulate the chart's size and location you can use ' something like this to align it with a cell ' there are also Height, Top, Left, Width, etc. cObj.Top = Range("A1").Top cObj.Left = Range("A1").Left '## To manipulate it's size, you can work with ' there are also Height, Top, Left, etc. properties, etc. cObj.Width = 500 cObj.Height = 300 '## Manipulating the PlotArea, etc. ' there are also Height, Top, Left, etc. properties, etc. cht.PlotArea.Width = 450 cht.PlotArea.Height = 250 '## Add series to the chart Set srs = cht.SeriesCollection.NewSeries srs.Name = "=""target""" srs.XValues = "=MacroParty!$R$4:$R$55" srs.Values = "=MacroParty!$S$4:$S$55" '## "srs" will refer to SeriesCollection(1) until/unless you ' assign it to something else... '... like now, we want to add another series, ' so we will just assign another NewSeries to the "srs" variable ' and work with the variable srs. Set srs = cht.SeriesCollection.NewSeries srs.Name = "=""current""" srs.XValues = "=VA05NDump!$G$2:$G$833" srs.Values = "=VA05NDump!$G$2:$G$833" End Sub