Dear R,
There is no optimum access to this problem generally. The actualization of
categories and labels is no easy job. Still, you stimulated me to accomplish
something that I had been planning long ago, just because I need it myself.
It is advantageous here to come out from user-define chart template, which
you can embroider with all chart format details. You must, first of all,
create such a chart on base of one of your worksheets, and declare it as
user-defined one, under a proper name. The job of pasting the chart into a
worksheet with data is to be done with a further, following macro.
The macro supposes the data in individual worksheets are arranged invariably
into the same columns. These columns must be preset as ValCol, CatCol values
(and LabelCol - if the labels do exist) in the code. The first data row must
be preset too; note, however, that the data count in the worksheet can now be
variable. The last thing is setting the name of your chart template.
The macro respects the chart type; different sorts require different
treatment.
After all the adaptation, simply deploy the macro within each data worksheet
activated.
Option Explicit
Sub AddUserChart()
'Petr Bezucha, 2009
Dim ASName As String, RCFormula As String, ValSource As Range, _
ValCol As Long, CatCol As Long, LabelCol As Long, FirstRow As Long, _
LastRow As Long, ChType As Long, UserChartName As String, _
S As Worksheet, I As Long
'(manual) declaration of:
ValCol = 2 'column with values
CatCol = 1 'column with categories (or X-values)
LabelCol = 3 'column with labels (if exist)
FirstRow = 1 'first row of values
UserChartName = "MyUserChartName"
ASName = ActiveSheet.Name
Set S = Sheets(ASName)
LastRow = Cells(FirstRow, ValCol).End(xlDown).Row
Charts.Add
With ActiveChart
.ApplyCustomType ChartType:=xlUserDefined, TypeName:=UserChartName
Select Case .ChartType
Case xlXYScatter, xlXYScatterLines, xlXYScatterLinesNoMarkers, _
xlXYScatterSmooth, xlXYScatterSmoothNoMarkers
Set ValSource = Union(Range(S.Cells(FirstRow, CatCol), _
S.Cells(LastRow, CatCol)), _
Range(S.Cells(FirstRow, ValCol), S.Cells(LastRow, ValCol)))
.SetSourceData Source:=ValSource
.Location Where:=xlLocationAsObject, Name:=ASName
If ActiveChart.SeriesCollection(1).HasDataLabels Then
For I = 1 To LastRow - FirstRow + 1
ActiveChart.SeriesCollection(1).DataLabels(I).Text = _
S.Cells(FirstRow + I - 1, LabelCol).Value
Next I
End If
Case Else
Set ValSource = Range(S.Cells(FirstRow, ValCol), _
S.Cells(LastRow, ValCol))
.SetSourceData Source:=ValSource
.Location Where:=xlLocationAsObject, Name:=ASName
RCFormula = "C" & CStr(CatCol)
RCFormula = "=" & ASName & _
"!R" & CStr(FirstRow) & RCFormula & ":R" & CStr(LastRow) _
& RCFormula
ActiveChart.SeriesCollection(1).XValues = RCFormula
With ActiveChart.SeriesCollection(1).DataLabels
If .ShowValue Then .ShowValue = True
If .ShowCategoryName Then .ShowCategoryName = True
End With
End Select
End With
End Sub