Customzing the Charts using VBA - vba

I have a sheet with Pivot table and I am creating an Column stacked chart from the table.
I would like to change the colours of Legend entries in chart and would like to have an title for the chart every time I create the chart.
I tried the below code and I'm getting
Object variable or with block variable not set
I get the error in the line
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(155, 213, 91)
Could anyone, tell me how I could create chart for my requirements. I have added an image of my current chart and required chart.
Sub chart11()
Dim sh As Shape
Dim cht As Chart
If ActiveSheet.PivotTables.Count = 0 Then Exit Sub
Set ptable = ActiveSheet.PivotTables(1)
Set ptr = ptable.TableRange1
Set sh = ActiveSheet.Shapes.AddChart
sh.Select
With ActiveChart
.SetSourceData ptr
.ChartType = xlColumnStacked
End With
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(155, 213, 91)
cht.Axes(xlCategory).MinimumScale = 5
cht.Axes(xlCategory).MaximumScale = 40
cht.HasTitle = True
cht.ChartTitle.Text = "Default Chart"
End Sub
This is the chart generated by my code now, if I comment the error line:
I would like to have a chart of this type with change in colour legends and chart title:

You can't use cht.Axes(xlCategory).MinimumScale = 5 and MaximumScale.
Because Pivot chart do not assist Scatterchart.
Only in scatter chart, you can set xlCategory Scale.
Sub chart11()
Dim sh As Shape
Dim cht As Chart
If ActiveSheet.PivotTables.Count = 0 Then Exit Sub
Set ptable = ActiveSheet.PivotTables(1)
Set ptr = ptable.TableRange1
Set sh = ActiveSheet.Shapes.AddChart
sh.Select
Set cht = ActiveChart
With cht
.SetSourceData ptr
.ChartType = xlColumnStacked
End With
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(255, 0, 0) '<~~ Red
cht.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(0, 255, 0) '<~~ green
'cht.Axes(xlCategory).MinimumScale = 5
'cht.Axes(xlCategory).MaximumScale = 40
cht.HasTitle = True
cht.ChartTitle.Text = "Default Chart"
End Sub

Related

Error i n creating chart (Double Creation)

I am trying to create a chart on my sheet Monthprepare.
I am using the below code.
I have the code , behind the button with several other calling functions.
The problem is, whenever I am creating the chart, it is creating them twice.
I am left confused what would be the reason.
Could someone help to figure it out.
Sub chartmonthprep()
Dim cht As Chart
Dim stable As PivotTable
Dim pt, sh
If ActiveSheet.PivotTables.count = 0 Then Exit Sub
Set stable = ActiveSheet.PivotTables(2)
Set pt = stable.TableRange1
Set sh = ActiveSheet.ChartObjects.Add(Left:=250, _
Width:=400, Top:=20, Height:=250)
sh.Select
Set cht = ActiveChart
With cht
.SetSourceData pt
.ChartType = xlColumnStacked
End With
cht.FullSeriesCollection(1).Name = "Average of Red"
cht.SeriesCollection(1).HasDataLabels = True
cht.SeriesCollection(2).HasDataLabels = True
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(0, 255, 0)
cht.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
cht.HasTitle = True
cht.ChartTitle.Text = " Result"
End Sub
Try like this:
Sub chartmonthprep()
If ActiveSheet.ChartObjects.Count > 1 Then Exit Sub
'the rest of your code here --v
Dim cht As Chart
Dim stable As PivotTable
End Sub
It will make sure that it is only 1 chart.
You can loop for each Pivot Table in a sheet with this:
Sub PivotTable()
Dim sh As Worksheet
Dim pvt As PivotTable
Set sh = ThisWorkbook.Sheets("Sheet1")
For Each pvt In sh.PivotTables
MsgBox pvt.Name
'do something
Next pvt
End Sub

Remove the blank row values in chart

I am generating a chart from table. the table rows are not completely filled.
so when I am generating an chart, I get the value of not filled columns also as "0". I would like to remove the "0" (value of blank rows") in my chart. Is
there a way I can do this? any lead would be helpful
Sub chartResult()
Dim rng As Range
Dim cht As Object
Set rng = ActiveSheet.Range("B2:D53")
ThisWorkbook.Sheets("Result").ChartObjects.delete
Set sh = ActiveSheet.ChartObjects.Add(Left:=440, _
Width:=600, _
Top:=340, _
Height:=250)
sh.Select
Set cht = ActiveChart
With cht
.SetSourceData Source:=rng
.ChartType = xlColumnClustered
End With
cht.SeriesCollection(1).name = "Ov"
cht.SeriesCollection(2).name = "O"
cht.SeriesCollection(3).name = "To"
cht.SeriesCollection(1).HasDataLabels = True
cht.SeriesCollection(2).HasDataLabels = True
cht.SeriesCollection(3).HasDataLabels = True
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(72, 118, 255) '<~~ Red
cht.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
cht.SeriesCollection(3).Format.Fill.ForeColor.RGB = RGB(0, 167, 0)
cht.HasTitle = True
cht.ChartTitle.Text = "Result "
End Sub
Try the property Chart.DisplayBlanksAs and set xlNotPlotted.
So in the code the change looks some what as shown below in with statement.
With cht
.SetSourceData Source:=rng
.ChartType = xlColumnClustered
.DisplayBlanksAs = xlNotPlotted //ADD THIS STAEMENT.
End With
#Jenny - I can't guarantee this will work, I don't work with charts, but give it a try.
With cht
.SetSourceData Source:=rng
.ChartType = xlColumnClustered
.PivotItems("0").Visible = False
End With

Formatting with Charts

I have a sheet and I am generating the Chart from a table.
I would like to generate 2 charts. One chart with absolute numbers and other chart for the same data with Percentage.
Right now, for this, I am using two code, just by adding a line for generating the chart with Y.axis in percentage.
I would like to define column where my chart will start (for eg: chart1 from G7) and chart2 from G15. (I don't have this in my code)
I also, would like to define the length , height and width for my chart.(I don't have this in my code)
It would be great if you can help me add this requirement and do it In a single program.
Sub chartstatus()
Dim rng As Range
Dim cht As Object
Set rng = ActiveSheet.Range("A2:E53")
Set sh = ActiveSheet.Shapes.AddChart
sh.Select
Set cht = ActiveChart
With cht
.SetSourceData Source:=rng
.ChartType = xlColumnClustered
cht.Axes(xlSecondary).TickLabels.NumberFormat = "0.0%"
End With
cht.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(255, 255, 255) '<~~ Red
cht.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
cht.SeriesCollection(3).Format.Fill.ForeColor.RGB = RGB(0, 255, 0)
cht.HasTitle = True
cht.ChartTitle.Text = "Result 2017"
End Sub
I use the same code, deleting the line to generate the second chart
cht.Axes(xlSecondary).TickLabels.NumberFormat = "0.0%"
The easier way if to use the ChartObject to create and define the chart, and then modify all it's properties (such as position and dimension).
The code below will create the first chart, place it in Cell "G7", and I modifed it's dimensions to show you the properties you need to modify.
You can add another one for the second chart (with an easy copy>>paste).
Code
Option Explicit
Sub chartstatus()
Dim Rng As Range
Dim ChtObj As ChartObject
Set rng = ActiveSheet.Range("A2:E53")
' use ChartObject instead of shape
Set ChtObj = ActiveSheet.ChartObjects.Add(100, 100, 500, 500) '<-- default dimension and location >> can modify later
With ChtObj
.Chart.ChartType = xlColumnClustered
.Chart.SetSourceData Rng
With .Chart
.Axes(xlSecondary).TickLabels.NumberFormat = "0.0%"
.SeriesCollection(1).Format.Fill.ForeColor.RGB = RGB(255, 255, 255) '<~~ Red
.SeriesCollection(2).Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
.SeriesCollection(3).Format.Fill.ForeColor.RGB = RGB(0, 255, 0)
.HasTitle = True
.ChartTitle.Text = "Result 2017"
End With
' set position of the chart to Cell G7
.Top = Range("G7").Top
.Left = Range("G7").Left
' change the dimensions of the chart
With .Chart.ChartArea
.Width = 1060
.Height = 420
End With
End With
End Sub
For changing the chart location :
vba to add a shape at a specific cell location in Excel
For chart size:
sh.Width =100
sh.Height =100

mulit plot from different sheets in one chart with 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 ; )

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