mulit plot from different sheets in one chart with VBA - vba

My problem is that I want to make many graph in one chart but the data is from different sheets.
At the moment my code can only take multi data from one sheet, meaning I can plot 2 graph from one sheet.
My code at the moment is:
Sub ChartSheet()
Dim ChartSheet1 As Chart
Set ChartSheet1 = Charts.Add
With ChartSheet1
.SetSourceData Source:=Sheets("Sheet1").Range("E12:E6232, Y12:Y6232")
.ChartType = xlLine
.HasTitle = True
.ChartTitle.Characters.Text = "Test Chart"
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "x"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "y"
End With
End Sub
What I want is to say:
.SetSourceData Source:=Sheets("Sheet1").Range("E12:E6232, Y12:Y6232")
.SetSourceData Source:=Sheets("Sheet2").Range("D12:E23")
.SetSourceData Source:=Sheets("Sheet3").Range("Y12:Y6232, G27:G496, H3:5977")
and so on..
But when I do this my code it only print the last line from .SetSoureData
Hope some of you can help me work around this, Many thank in advarnce :)
Update:
I found abit of a work around by looping but this is not my total answer
But here is my other code:
Sub MultiSheetPlot()
Dim cht As Chart, s As Series, xRng As Range
Dim i As Long, chartName As String
Set cht = Charts.Add
cht.ChartType = xlLine
For i = 1 To 3
chartName = "Sheet" & i
Set xRng = Sheets("Sheet1").Range("A1:A20, C1:C20")
With cht.SeriesCollection.NewSeries()
.Values = xRng
.Name = chartName
End With
Next i
End Sub
the problem in this code is that it ignores the last range I define like the C10:C20

Responding to your latest update, I have a Sub that creates a series each time it's called from MultiSheetPlot Sub.
You can actually add more parameters to this Sub (as long as you remeber to pass them in the Calling).
Option Explicit
Dim cht As Chart
Sub MultiSheetPlot()
Set cht = Charts.Add
cht.ChartType = xlLine
' call the series creation chart function (each time for each series you want to add to the existing chart
Call Create_SeriesChart("Sheet1", Sheets("Sheet1").Range("E12:E6232"), 1, True, msoThemeColorText1)
Call Create_SeriesChart("Sheet1", Sheets("Sheet1").Range("Y12:Y6232"), 1, True, msoThemeColorText1)
End Sub
' ------ this Sub creates a series to the chart, it receives the following parameters: ------
' 1. seriesName - String
' 2. serValues - Range
' 3. lineWeight - Double (the weight of the line)
' 4. lineVis - Boolean (if you want to hide a certail series)
' 5. lineColor - MsoColorType (using the current's PC Theme colors
Sub Create_SeriesChart(seriesName As String, serValues As Range, lineWeight As Double, lineVis As Boolean, lineColor As MsoColorType)
Dim Ser As Series
Set Ser = cht.SeriesCollection.NewSeries
With Ser
.Name = seriesName
.Values = serValues
.Format.Line.Weight = lineWeight
If lineVis = True Then
.Format.Line.Visible = msoTrue
Else
.Format.Line.Visible = msoFalse
End If
.Format.Line.ForeColor.ObjectThemeColor = lineColor ' Line color Black
End With
End Sub

My solution is use Name of plage, you can give a name of your range
Like in my photo :
Everytime when you want to use these datas you just need call them
Like this plage i gived them name Poste_EtatDeLaDemande
When i want to use these elements i just call it like Range("Poste_EtatDeLaDemande") Excel will find it you don't need tell them where it is anymore ; )

Related

Black Border around the Column Chart in VBA

I try to set a black border around the Column chart from my Vba CODE. This is what i have now. The last row where i set Border.ColorIndex obviously does not work. Currently the column looks like this.
I want it to look like this.
Here is my code.
ActiveSheet.Cells(10000, 10000).Select
ActiveSheet.Shapes.AddChart.Select
With ActiveChart ' clear SeriesCollection
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
End With
ActiveChart.ChartType = xlColumnClustered
ActiveChart.PlotVisibleOnly = True
ActiveChart.Location Where:=xlLocationAsNewSheet, Name:="Plottt" ' rename chart sheets
' create SeriesCollection for each line
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).Name = "Hallo"
ActiveChart.SeriesCollection(1).XValues = breaks
ActiveChart.SeriesCollection(1).Values = freq
ActiveChart.ChartGroups(1).GapWidth = 0
ActiveChart.ChartGroups(1).Border.ColorIndex = 3
Also i would like to reduce the step size from my code. Help with this would also be appreciated.
To set the border color for a SeriesCollection(1) use the line below:
ActiveChart.SeriesCollection(1).Format.Line.ForeColor.RGB = RGB(255, 0, 0)
Note: it's better to not use ActiveChart, and it's "relatives". Instead use referenced objects. In this case use a ChartObject.
Simple reference code:
Dim Chtobj As ChartObject
' modify "Chart_Data" Name to your Sheet, and "Chart 1" to your chart's name
Set Chtobj = Sheets("Chart_Data").ChartObjects("Chart 1")
With Chtobj
' modify the chartobject properties here...
' modify the major unit of X-axis
.Axes(xlCategory).MajorUnit = 5 '<-- modify to whatever value you want
' modify the minor unit of X-axis
.Axes(xlCategory).MinorUnit = 1
End With
I am not sure why the border isn't showing, though I suspect that there must be a property that determines its visibility or thickness.
For cleaning up your code though, try this:
Dim oChart as Object
ActiveSheet.Cells(10000, 10000).Select
Set oChart = ActiveSheet.Shapes.AddChart
With oChart' clear SeriesCollection
Do Until .SeriesCollection.Count = 0
.SeriesCollection(1).Delete
Loop
.ChartType = xlColumnClustered
.PlotVisibleOnly = True
.Location Where:=xlLocationAsNewSheet, Name:="Plottt" ' rename chart sheets
' create SeriesCollection for each line
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.Name = "Hallo"
.XValues = breaks
.Values = freq
End With
With .ChartGroups(1)
.GapWidth = 0
With .Border
.ColorIndex = 3
' You may need the LineStyle property of the border
' https://msdn.microsoft.com/en-us/library/office/ff821622.aspx
.Linestyle = xlContinuous
End With
End With
End With ' Ends the with block for the entire chart
This should not only clean up your code quite a bit and make it easier to debug, but I have had cases where an object I am working with doesn't update properly if I try to update it's properties outside of a with block. I am not sure if there is a reason for this or not, but I err on the side of using the With block just in case.

To generate scatter xy graph in excel using macro

I have written a macro to generate graph in excel but i want that graph to be generated in the next sheet not in the same sheet.i have pasted my macro below its working properly i just want it to be in the next sheet. please provide me some solution*
Sub LumData1()
If IsEmpty(Range("B2,D2")) = False Then
Range("B:B,D:D,H:H,I:I,J:J,M:M").Select
Range("M1").Activate
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlXYScatterSmoothNoMarkers
ActiveChart.SetSourceData Source:=Sheets(ActiveSheet.Name).Range( _
"$B:$B,$D:$D,$H:$H,$I:$I,$J:$J,$M:$M" _
)
ActiveChart.Location Where:=xlLocationAsObject, Name:=ActiveSheet.Name
With ActiveChart.ChartArea
.Width = 1060
.Height = 420
.Left = 0
End With
ActiveChart.SeriesCollection(1).Select
ActiveChart.SeriesCollection(1).AxisGroup = 2
ActiveChart.SeriesCollection(5).Select
ActiveChart.SeriesCollection(5).AxisGroup = 2
ActiveChart.Axes(xlCategory, xlPrimary).HasTitle = True
ActiveChart.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
ActiveChart.Axes(xlValue, xlPrimary).HasTitle = True
ActiveChart.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Value"
ActiveChart.Axes(xlCategory).TickLabels.Orientation = 45
End If
End Sub
My answer covers not only how to solve your question in your post, but how to automatically define and set-up charts in VBA in a “cleaner” and safer way.
It's better if you avoid using ActiveSheet, Select, and ActiveChart. Instead always use referenced objects, in this case Worksheets and ChartObject. E.g Dim ChtObj As ChartObject , and later set it with Set ChtObj = ShtCht.ChartObjects.Add(100, 100, 500, 500) , where ShtCht is the worksheet where you create your chart.
Once you defined and set your ChartObject, its quite easy to modify its properties by using the With ChtObj , and also nested properties, by adding With .Chart.ChartArea under the first With statement.
Code
Option Explicit
Sub LumData1()
Dim ChtObj As ChartObject
Dim ShtSrc As Worksheet
Dim ShtCht As Worksheet
' change "Sheet1" to your sheet's name (where you have your chart's data)
Set ShtSrc = Worksheets("Sheet1") ' <-- I preffer not to work with ActiveSheet
'Set ShtCht = Worksheets("Sheet2") ' <-- set the chart's destination worksheet
Set ShtCht = Worksheets.Add ' <-- create a new worksheet to place the chart
ShtCht.Name = "Chart"
If Not IsEmpty(ShtSrc.Range("B2,D2")) Then
Set ChtObj = ShtCht.ChartObjects.Add(100, 100, 500, 500)
With ChtObj
.Chart.ChartType = xlXYScatterSmoothNoMarkers
.Chart.SetSourceData ShtSrc.Range("$B:$B,$D:$D,$H:$H,$I:$I,$J:$J,$M:$M")
' set position of the chart to Cell M1
.Top = ShtCht.Range("M1").Top
.Left = ShtCht.Range("M1").Left
' modify chart position and dimensions
With .Chart.ChartArea
.Width = 1060
.Height = 420
.Left = 0
End With
With .Chart
.SeriesCollection(1).AxisGroup = 2
.SeriesCollection(5).AxisGroup = 2
.Axes(xlCategory, xlPrimary).HasTitle = True
.Axes(xlCategory, xlPrimary).AxisTitle.Characters.Text = "Date"
.Axes(xlValue, xlPrimary).HasTitle = True
.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = "Value"
.Axes(xlCategory).TickLabels.Orientation = 45
End With
End With
End If
End Sub
edited after OP's clarification he has to make a new sheet to host the chart into
to stick to your code as much as possible:
remove ActiveChart.Location Where:=xlLocationAsObject, Name:=ActiveSheet.Name
place the following code right before End if
Dim myChart As Chart: Set myChart = ActiveChart
Worksheets.Add
myChart.Location Where:=xlLocationAsObject, Name:=ActiveSheet.Name

excel VBA Chart Formatting - need to change the width of a line

I am trying to write code that will format a chart (myChart). Series line 2 and 4 are the 2 that I need to format so their weight = 1. I have tried following with no luck.
myChart.fullseriescollection(2).format.line.weigth = 1
I am pretty new to VBA, and I have never tried to reference chart object before, so I am unfamiliar with the proper syntax.
Thanks! See my code below.
Sub myChart()
Dim myChart As Chart, cht As ChartObject
Dim rngChart As Range, destSht As String
Dim rngData As Range
destSht = ActiveSheet.Name
Set myChart = Charts.Add
Set myChart = myChart.Location(where:=xlLocationAsObject, Name:=destSht)
With ActiveSheet.ListObjects("Table1").DataBodyRange
Set rngData = Union(.Columns(2), .Columns(9), .Columns(10), .Columns(11), .Columns(12))
End With
With myChart
.SetSourceData Source:=rngData, PlotBy:=xlColumns
.ChartType = xlColumnClustered
.ChartStyle = 209
*****Below is the first series line that I want to format*****
With .FullSeriesCollection(2)
.ChartType = xlLine
.AxisGroup = 1
End With
With .FullSeriesCollection(3)
.ChartType = xlLineMarkers
.AxisGroup = 2
End With
*****2nd line I want to format*****
With .FullSeriesCollection(4)
.ChartType = xlLine
.AxisGroup = 2
End With
End With
ActiveSheet.ChartObjects(1).Activate
Set cht = ActiveChart.Parent
Set rngChart = Range("A1100:K1115")
cht.Left = rngChart.Left
cht.Top = rngChart.Top
cht.Width = rngChart.Width
cht.Height = rngChart.Height
Range("A2").Select
End Sub
With .FullSeriesCollection(2)
.ChartType = xlLine
.AxisGroup = 1
.Format.Line.Weight = 5
End With
Worked fine for me in Office 2016.
I would have commented, but I do not have a high enough reputation yet

Error at creating simple x y smooth chart

I am trying to create a dynamic chart that will change the data set with time, but I am stuck at the first step which is creating a simple chart with a certain limited number of points.
My x values and Y values are at rows 3 and 5.
The code I am trying to run is to create the chart in the same worksheet I am using:
Sub UpdateChart()
Dim ChtObj As ChartObject
Set ChtObj = ActiveSheet.ChartObjects("Bending Moment along " & ActiveSheet.Name) 'Adjust chart name to your chart
With ChtObj.Chart
.ChartType = x1XYScatterSmooth
.SetElement msoElementLegendNone
.Axes(xlValue).MinimumScale = 0
.Axes(xlValue).MaximumScale = 5
.SeriesCollection.NewSeries
.SeriesCollection(1).Name = "Bending moment"
.SeriesCollection(1).Values = Range("D3:H3")
.SeriesCollection(1).XValues = Range("D5:H5")
End With
End Sub
I am getting error run-time 5, invalid procedure call or argument? This happens at the line of: With ChtObj.Chart
You have a typo in the first line of the With statement. Hard to see, but there is a 1 instead of an l.It should be
.ChartType = xlXYScatterSmooth

Generating dynamic charts with VBA

I have to create almost 200 charts of time series. So I tried to write a macro that finishes most of the work I need to do.
I generated names for the time series like this as an example:
Name:= AKB_ExampleA
The name refers to a dynamic range which I declared with this formula:
=OFFSET('sheet1'!$C$7:$C$137;0;0;COUNT('sheet1'!$C$7:$C$206))
So now to the macro I coded so far:
Sub graphik_erstellen()
Call graphik1("AKB")
End Sub
Sub graphik(Name As String)
'
Dim Ch As Chart
Dim RngToCover As Range
Set Ch = charts.Add
Set Ch = Ch.Location(Where:=xlLocationAsObject, Name:="Charts")
With Ch
.ChartType = xlLine
.SetSourceData Source:=Range(Name & "_ExampleA")
.SeriesCollection(1).XValues = Range("Datum_Volumen")
.SeriesCollection(1).Name = "SERIES1"
.FullSeriesCollection(1).Select
With Selection.Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(192, 0, 0)
.Transparency = 0
End With
.HasTitle = True
.ChartTitle.Text = Name & ", Volumen (nach Korrektur)"
.HasLegend = True
.Legend.Position = xlLegendPositionBottom
.Legend.Select
Selection.Format.TextFrame2.TextRange.Font.Size = 11
Selection.Format.TextFrame2.TextRange.Font.Bold = msoTrue
With .Parent
.top = 100
.left = 100
.height = 287.149606299
.width = 543.685039370078
.Name = Name & "_chart"
End With
End With
End Sub
My problem is, that if I do that, the dynamic range is not really considered. It takes the range of the name (which is $C$7:$C$137) but it should refer to the name itself (in order to be dynamic).
So if I click on the chart to see the series, the series values are declared as: ='sheet1'!$C$7:$C$137 instead of ='sheet1'!ExampleA.
I would be really, really grateful if somebody could help me out.
Best
Elio
I have rearranged a few lines of code and tried to place comments refering to them as well.
Let me know what works. Youjust might need to change SeriesCollection to FullSeriesCollection. Other than that the code works in my Excel 2010.
The first Sub I just get the Range size according to the data available in Column "C" from Row 7.
Let me know.
Option Explicit
Sub graphik_erstellen()
'You always want to use direct reference to a sheet/range chart
'Refering to the WorkBook they are in and the worksheet as well.
'especially if you are opening multiple WorkBooks / Sheets
Dim CurrentWorkSheet As Worksheet
Set CurrentWorkSheet = Workbooks("Book1").Worksheets("Sheet1")
'Dynamically finding the end of the data in Column C
Dim LastRow As Long
LastRow = CurrentWorkSheet.Cells(CurrentWorkSheet.Rows.Count, "C").End(xlUp).Row
'Setting the range using the document reference aswell
Dim AKB As Range
Set AKB = Workbooks("Book1").Worksheets("Sheet1").Range(Cells(7, "C"), Cells(LastRow, "C"))
Call graphik(AKB)
End Sub
Sub graphik(Name As Range)
Dim DataChart As Chart
Dim RngToCover As Range
Set DataChart = Workbooks("Book1").Charts.Add
'With Excel 2010 the line above will automatically add the chart as a sheet and not aobject in a sheet
'Set DataChart = DataChart.Location(Where:=xlLocationAsObject, Name:="Charts")
With DataChart
.Name = "Charts" ' This will be the Name of the CHart Tab
.ChartType = xlLine
.SetSourceData Source:=Name
'You can see below I avoided the Select and Selection
With .SeriesCollection(1)
'Using Offset I just used the data one cell to the left of the range
.XValues = Name.Offset(0, -1)
.Name = "SERIES1"
With .Format.Line
.Visible = msoTrue
.ForeColor.RGB = RGB(192, 0, 0)
.Transparency = 0
End With
End With
.HasTitle = True
.ChartTitle.Text = "MIDDEL TOP TEXT" 'Name & ", Volumen (nach Korrektur)"
.HasLegend = True
With .Legend
.Position = xlLegendPositionBottom
.Format.TextFrame2.TextRange.Font.Size = 11
.Format.TextFrame2.TextRange.Font.Bold = msoTrue
End With
'Not sure about this, it doesnt work in my Excel 2010
'
With .Parent
.Top = 100
.Left = 100
.Height = 287.149606299
.Width = 543.685039370078
.Name = Name & "_chart"
End With
End With
End Sub
Let me know what your intention is for the Sheet and Chart names and then I can help with getting that to what you need as well.