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

时间:2014-05-16 00:13:13

标签: excel vba excel-vba

我正在尝试将图表插入到可显示4列信息的工作表中。

x轴具有日期,y轴具有$ figure数量。 这就是我记录一个宏(它至少显示了我想要的):

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的新手并且依赖于暴力方法。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:2)

好的,你可以稍微清理一下。宏录制器很棒,因为它可以帮助你看到你需要做什么,但它只不过是简单地复制键击或鼠标点击,而VBA中的编程点应该是直接使用对象 - 比模仿按键更有效率。

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

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