VBA Chart setsourcedata

2019-08-29 10:48发布

问题:

I have to write a VBA script to define Data Source for a chart, but I am not a VBA programmer. In my workbook, I have many sheets and many sheets have many charts. In my VBA I have to define data source for every chart. For this, I want to know whether I can write in my module the below statement:

<sheet-name>.<chart-name>.SetSourceData Source ='CPU_UTIL'!$A$1:$A$31,'CPU_UTIL'!$N$1:$O$31

Whether this syntax is correct and can I use it directly?

回答1:

First of all, I am a little hesitant to answer this question since there are lots of resources out there you could find. For a basic start you can use the following code to set 'SetSourceData' source for a Chart based on B to H column data. To do this, you should already have your chart in Sheet1 and it's Chart Type is already chosen using the Chart Wizard. Otherwise you could write adding the chart, setting up the Chart Type, setting source data, formatting/colours, everything using VBA as well. (All depends on your intention given the technology required is available)

Sub SetMyChartSourceData()
  With Sheets("Sheets1)
    .ChartObjects(1).Chart.SetSourceData Source:= .Range("B2:H100"), PlotBy:=xlColumns
  End With
End Sub

You mentioned "VBA" Script but looking at your code, it's "VB"Script. Then you can search how to modify an existing chart using VBSCript in Excel. However, I recommend you to stick to VBA, if coding is really required.

In the first place you can set source without a vba code. So Please let us know why you are intending to use VBA? Usually most questions are answered quickly. But you should wonder why yours a relatively pretty straightforward question didn't get any respond for two hours...

Some main(MSDN) and good references for VBA Charts in Excel:

  • Microsoft Chart Library

  • My favourite Excel Chart Blog: