VBA code doesnt add category from defined range in line chart - excel

I am trying to create a line chart through the use of VBA,i do this by using the attached code, I list the category i want in the rng, however it doesn't automatically select this to be the category, i want columns 4,5 to be displayed on the chart and 3 to be the category.
Sub CreateGBPChart()
'PURPOSE: Create a chart (chart dimensions are not required)
Dim rng As Range
Dim cht As Object
Dim wks As Worksheet, wks2 As Worksheet
Set wks = Sheet2
Set wks2 = Sheet5
'data range for the chart
lastrow = wks.Cells.Find("*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
Set rng = Range(wks.Cells(10, 3), wks.Cells(lastrow, 5))
'Create a chart
Set cht = wks2.ChartObjects.Add( _
Left:=wks2.Range("K18").Left, _
Width:=480, _
Top:=wks2.Range("K18").Top, _
Height:=200)
' chart data
cht.Chart.SetSourceData Source:=rng
'cht.Chart.Axes(xlCategory).CategoryNames = Range(wks.Cells(10, 3), wks.Cells(lastrow, 3))
'Determine the chart type
cht.Chart.ChartType = xlXYScatterLines
'chart title
cht.Chart.HasTitle = True
'Change title
cht.Chart.ChartTitle.Text = "GBP Price"
'Remove Legend
'cht.Legend.Delete
cht.Chart.Parent.Name = "GBPTable"
'adjust the min val
cht.Axes(xlValue).MinimumScale = 1
'format fontsize'
cht.Chart.ChartArea.Format.TextFrame2.TextRange.Font.Size = 8
'cht.Chart.chartSeriesCollection(1).Line.Width = 4
'cht.Chart.chartSeriesCollection(2).Format.Line.Width = 4
End Sub

Try this:
' cht.Chart.SetSourceData Source:=rng
cht.Chart.SetSourceData Source:=wks.Range(wks.Cells(10, 4), wks.Cells(LastRow, 5))
' Add lines
cht.Chart.SeriesCollection(1).XValues = wks.Range(wks.Cells(10, 3), wks.Cells(LastRow, 3))
cht.Chart.SeriesCollection(2).XValues = wks.Range(wks.Cells(10, 3), wks.Cells(LastRow, 3))

Related

Excel VBA code for creating a chart object and plotting xyscatterline with data from different worksheets

I couldn't figure out what is wrong with the VBA code I created to plot data from worsheets that satisfying a condition on their name . xyscatter line to be created using data from column G as xvalues and column J as values.
I get error "Run-time error '1004': Application - defined or object-defined error"
Help is much appreciated as I will be doing this very often.
Thank you!
Sub charting()
Dim i, j, last_column, last_row As Integer
Dim sh As Worksheet
Dim cht As Chart
Dim xrng1, yrng1 As Range
Set cht = Charts.Add
i = 0
With cht
.ChartType = xlXYScatterLines
.Name = "cht1"
End With
For Each sh In ThisWorkbook.Worksheets
If LCase(sh.Name) Like "nov*" Or LCase(sh.Name) Like "bh*" Then
i = i + 1
With sh
last_row = .Cells(Rows.Count, 2).End(xlUp).Row
Set xrng1 = .Range(.Cells(2, 7), .Cells(last_row, 7))
Set yrng1 = .Range(.Cells(2, 10), .Cells(last_row, 10))
End With
End If
cht.Activate
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(i).XValues = xrng1
ActiveChart.FullSeriesCollection(i).Values = yrng1
ActiveChart.FullSeriesCollection(i).Name = sh.Name
Next sh
End Sub

VBA place two charts on one sheet

How can I place two different sheets on one page.
I create a chart with this code
'Create a chart
Set cht = Worksheets("Dashboard").Shapes.AddChart2
'Set cht = ActiveSheet.Shapes.AddChart2
With cht
.Chart.SetSourceData Source:=rng 'Give chart some data
.Chart.ChartType = xlColumnStacked 'Determine the chart type
.Chart.PlotBy = xlColumns
.ScaleHeight 1.7, msoFalse
.Chart.SetElement (msoElementLegendRight)
.Chart.ChartTitle.Text = Range("E1")
End With
Worksheets("Dashboard").Select
ActiveSheet.ChartObjects(1).Name = "FalseCall"
Range("A1") = ActiveSheet.ChartObjects(1).Name
ActiveSheet.Shapes("FalseCall").Left = Range("A1").Left
ActiveSheet.Shapes("FalseCall").Top = Range("A1").Top
ActiveSheet.Shapes("FalseCall").Width = Range("A1:G1").Width
ActiveSheet.Shapes("FalseCall").Height = Range("A1:A26").Height
It will add a chart on sheet "Dashboard".
Next I want to add a new chart with another name on the same page on H1 with
ActiveSheet.ChartObjects(1).Name = "Ng"
The existing chart will be renamed with the name of the second Chart and moves to H1, instead of the new chart is getting that name and moving the H1
It's not more complicated than repeating the steps with new ranges specified.
Sub InsertTwoCharts()
Dim ws As Worksheet
Set ws = Worksheets("Dashboard")
' CHART 1
' range that chart will cover
Dim ChtRng1 As Range
Set ChtRng1 = ws.Range("A1:G26")
' chart data range
Dim ChtData1 As Range
Set ChtData1 = Worksheets("Whatever").Range("A1:E12") ' or whatever
' insert and modify the chart
Dim cht1 As ChartObject
Set cht1 = ws.Shapes.AddChart2
With cht1
.Name = "FalseCall"
.Chart.SetSourceData Source:=ChtData1, PlotBy:=xlColumns
.Chart.ChartType = xlColumnStacked
.Chart.SetElement msoElementLegendRight
.Chart.ChartTitle.Text = ws.Range("E1").Value ' pick a worksheet and cell
.Left = ChtRng1.Left
.Top = ChtRng1.Top
.Width = ChtRng1.Width
.Height = ChtRng1.Height
End With
' CHART 2
' range that chart will cover
Dim ChtRng2 As Range
Set ChtRng2 = ws.Range("H1:N26")
' chart data range
Dim ChtData2 As Range
Set ChtData2 = Worksheets("Whatever").Range("G1:K12") ' or whatever
' insert and modify the chart
Dim cht2 As ChartObject
Set cht2 = ws.Shapes.AddChart2
With cht2
.Name = "TrueCall"
.Chart.SetSourceData Source:=ChtData1, PlotBy:=xlColumns
.Chart.ChartType = xlColumnStacked
.Chart.SetElement msoElementLegendRight
.Chart.ChartTitle.Text = ws.Range("H1").Value ' pick a worksheet and cell
.Left = ChtRng2.Left
.Top = ChtRng2.Top
.Width = ChtRng2.Width
.Height = ChtRng2.Height
End With
End Sub

Looping through multiple tables which vary in length

I have the following table:
And a macro that loops through the first section of the table (rows 6-7) in order to create the Pie-Charts on the right. My target now is to loop through all other tables automatically as well. The next one would be in row11 and create a new Pie Chart for that row, then the next table (rows 15-16) and so on. The header of each table is always red. The problem is that the length of the tables vary, meaning for example in the table1 ("Build", A5:K7) there can be 2 rows like here or 50, but each time I need one PieChart for each row.
Currently I have the following working code for Table1 ("Build" A6:K79) to create the 2 PieCharts automatically, but Im unsure how to make one loop for all tables on the sheet.
Dim rownumber As Integer
Dim LabelRange As Range
Dim ValueRange As Range
Dim Chart As ChartObject
Dim LeftIndent As Long
Dim TopIndent As Long
Dim InhaltsRangeString As String
Dim LetzteZeile As Long
'Intialpositionen für Graphen
LeftIndent = 726
TopIndent = 60
rownumber = 6 'Anfang der Buildtabelle in Reihe 6 (Spalte 1)
Set LabelRange = ThisWorkbook.Worksheets("Testplan Überblick").Range("C5, E5, G5, I5")
Set TPsheet = Worksheets("Testplan Überblick")
Set ValueRange = Union(TPsheet.Cells(rownumber, 3), TPsheet.Cells(rownumber, 5), TPsheet.Cells(rownumber, 7), TPsheet.Cells(rownumber, 9))
'Loop through table 1 which always starts at row 6 (unlike the others which have no set starting point cause the ones before can vary in length!)
For rownumber = 6 To LetzteZeileFunktion Step 1 '"LetzteZeileFunktion" gives me the long value of the last row filled in table 1
Set Chart = Sheets("Testplan Überblick").ChartObjects.Add(Left:=180, Width:=270, Top:=7, Height:=210)
With Chart
.Chart.SetSourceData Source:=ValueRange
.Chart.ChartType = xlPie
.Chart.HasTitle = True
.Chart.SetElement (msoElementChartTitleAboveChart)
.Chart.ChartTitle.Text = Sheets("Testplan Überblick").Cells(rownumber, 1).Value
.Chart.FullSeriesCollection(1).XValues = LabelRange
.Left = LeftIndent
.Top = TopIndent
.Name = Sheets("Testplan Überblick").Cells(rownumber, 1).Value
End With
TopIndent = TopIndent + 225
Next rownumber
End Sub
Any ideas on how to loop through all the tables even though they can all differ in length (amount of rows filled with content for charts) would be greatly appreciated!
Cheers
Use the text in one of the headers to identify the start of the data rows and a blank in column A to end. I have used "testfall qty" in column B.
Option Explicit
Sub CreateCharts()
Const DATA = "Testplan Überblick"
Const ROW_START = 5
Const POSN_LEFT = 726
Const POSN_TOP = 60
Const COL = "B"
Const HEADER = "testfall qty"
Dim wb As Workbook, ws As Worksheet
Dim rngLabel As Range, rngValue As Range
Dim iRow As Long, iLastRow As Long, count As Integer
Dim oCht As ChartObject, sColA As String, bflag As Boolean
bflag = False
Set wb = ThisWorkbook
Set ws = wb.Sheets(DATA)
' scan down the sheet
iLastRow = ws.Cells(Rows.count, "A").End(xlUp).Row
For iRow = ROW_START To iLastRow
' look for Testfall Qty as header
sColA = ws.Cells(iRow, 1)
If LCase(ws.Cells(iRow, COL)) = HEADER Then
'set ranges
Set rngLabel = ws.Range("C1, E1, G1, I1").Offset(iRow - 1)
bflag = True
ElseIf Len(sColA) > 0 And bflag Then
' create chart
Set rngValue = ws.Range("C1, E1, G1, I1").Offset(iRow - 1)
Set oCht = ws.ChartObjects.Add(Left:=180, _
Width:=270, Top:=7, Height:=210)
With oCht
.Left = POSN_LEFT
.Top = POSN_TOP + (count * 255)
.Name = sColA
With .Chart
.SetSourceData Source:=rngValue
.SeriesCollection(1).XValues = rngLabel
.ChartType = xlPie
.HasTitle = True
.SetElement msoElementChartTitleAboveChart
.ChartTitle.Text = sColA
End With
End With
count = count + 1
Else
' end of chart data
bflag = False
End If
Next
MsgBox count & " Charts created", vbInformation
End Sub

Chart not showing data when selecting data with vba

I'm using VBA to update my chart. With VBA I select the data that should be shown in the chart. My code does select the data, but somehow my chart doesn't show anything. When I click on my chart end select "Select data" it does show selected data, bu somehow my chart is still empty. Because my chart is empty, the rest of my code doesn't work
My chart is a combo chart with both dataranges as bars, absolute on the primary axis and relative on the secondary axis.
Dim DataSite As Range
Dim DataAbsolute As Range
Dim DataRelative As Range
Set DataSite = Range(Cells(7, 1), Cells(7, 1).End(xlDown))
Set DataAbsolute = Range(Cells(7, 4), Cells(7, 4).End(xlDown))
Set DataRelative = Range(Cells(7, 5), Cells(7, 5).End(xlDown))
GraphsFrames.Select
For Each serie In cht.Chart.SeriesCollection
serie.Select
serie.Delete
Next serie
With cht.Chart
With .SeriesCollection.NewSeries
.XValues = DataSite
.Values = DataAbsolute
.Name = "Absolute"
.AxisGroup = 1
End With
With .SeriesCollection.NewSeries
.Values = DataRelative
.Name = "Relative"
.AxisGroup = 2
End With
.ChartGroups(1).GapWidth = 50
.ChartGroups(2).GapWidth = 300
.Refresh
End With
What can I do to make sure my chart shows the data selected?
Well, I don't know what GraphFrames is, so I ignored it. I made only minor adjustments to your code, below, and it worked just fine. I assume the data is on the active sheet, and so is the chart object you're adding data to.
Sub DoChartData()
Dim DataSite As Range
Dim DataAbsolute As Range
Dim DataRelative As Range
With ActiveSheet
Set DataSite = .Range(.Cells(7, 1), .Cells(7, 1).End(xlDown))
Set DataAbsolute = .Range(.Cells(7, 4), .Cells(7, 4).End(xlDown))
Set DataRelative = .Range(.Cells(7, 5), .Cells(7, 5).End(xlDown))
End With
Dim cht As ChartObject
Set cht = ActiveSheet.ChartObjects(1)
Dim serie As Series
For Each serie In cht.Chart.SeriesCollection
serie.Delete
Next serie
With cht.Chart
With .SeriesCollection.NewSeries
.XValues = DataSite
.Values = DataAbsolute
.Name = "Absolute"
.AxisGroup = 1
End With
With .SeriesCollection.NewSeries
.Values = DataRelative
.Name = "Relative"
.AxisGroup = 2
End With
.ChartGroups(1).GapWidth = 50
.ChartGroups(2).GapWidth = 300
End With
End Sub

How can I write a loop in vba for this code

59.30 15 16 17
1 1,162,912,036.90 1,248,737,016.99 1,306,573,912.08
2 245,665,383.94 261,416,880.69 276,613,283.05
3 393,313,441.29 379,169,039.15 418,680,492.19
4 13,920,572.74 14,464,854.92 15,120,474.58
5 54,501,581.55 56,319,351.21 58,832,588.24
6 15,165,376.28 11,694,942.56 10,809,661.03
7 194,397,643.30 170,427,013.85 182,567,862.46
8 15,165,376.28 11,694,942.56 10,809,661.03
9 2,079,876,036.00 2,142,229,099.38 2,269,198,273.62
3% 6%
There are 7 tables like the above data in one excel tab in different area.I want to create a stacked column chart for each table. I wrote a code to create. Just want to know is that possiable to use loop to solve this problem? Code attached.
Sub FormatChartNIX()
'PURPOSE: Create a chart (chart dimensions are not required)
Dim rng As Range
Dim cht As Object
Dim ser As Series
Dim tmpCHR As ChartObject
'Chart1
'Your data range for the chart
Set rng = ActiveSheet.Range("B8:E17")
'Create a chart
Set cht = ActiveSheet.Shapes.AddChart
'Give chart some data
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
'Determine the chart type
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(1).Top = .Range("C24").Top
.ChartObjects(1).Left = .Range("C24").Left
End With
ActiveSheet.ChartObjects(1).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("c1")
'Chart2
Set rng = ActiveSheet.Range("G8:J17")
Set cht = ActiveSheet.Shapes.AddChart
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(2).Top = .Range("H24").Top
.ChartObjects(2).Left = .Range("H24").Left
End With
ActiveSheet.ChartObjects(2).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("h1")
'Chart3
Set rng = ActiveSheet.Range("L8:o17")
Set cht = ActiveSheet.Shapes.AddChart
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(3).Top = .Range("M24").Top
.ChartObjects(3).Left = .Range("M24").Left
End With
ActiveSheet.ChartObjects(3).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("h1")
'Chart4
Set rng = ActiveSheet.Range("B82:E91")
Set cht = ActiveSheet.Shapes.AddChart
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(4).Top = .Range("C51").Top
.ChartObjects(4).Left = .Range("C51").Left
End With
ActiveSheet.ChartObjects(4).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("c75")
'Chart5
Set rng = ActiveSheet.Range("G82:J91")
Set cht = ActiveSheet.Shapes.AddChart
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(5).Top = .Range("H51").Top
.ChartObjects(5).Left = .Range("H51").Left
End With
ActiveSheet.ChartObjects(5).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("h75")
'Chart6
Set rng = ActiveSheet.Range("L82:o91")
Set cht = ActiveSheet.Shapes.AddChart
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(6).Top = .Range("M51").Top
.ChartObjects(6).Left = .Range("M51").Left
End With
ActiveSheet.ChartObjects(6).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("m75")
'Chart7
Set rng = ActiveSheet.Range("Q82:T91")
Set cht = ActiveSheet.Shapes.AddChart
cht.chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.chart.ChartType = xlColumnStacked
With ActiveSheet
.ChartObjects(7).Top = .Range("R51").Top
.ChartObjects(7).Left = .Range("R51").Left
End With
ActiveSheet.ChartObjects(7).Activate
ActiveChart.Axes(xlValue).Select
Selection.delete
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = ActiveSheet.Range("r75")
End Sub
Using named ranges and some arrays you can loop through it.
First, create named ranges for the ranges for each chart.
I added a small table in the spreadsheet and named each one the text in the first cell of the range (i.e., Chart1,... Chart7). The other ranges each go in the next cell, so the range named "Chart 1" is 4 cells.
(I also used the same ranges and cells that you did in your code above)
Chart1 B8:E17 C24 C1
Chart2 G8:J17 H24 H1
Chart3 L8:O17 M24 H1
Chart4 B82:E91 C51 C75
Chart5 G82:J91 H51 H75
Chart6 L82:O91 M51 R75
Chart7 Q82:T91 R51 R75
Sub FormatChartNIX_Modified()
Dim rng As Range
Dim cht As Object
Dim ser As Series
Dim tmpCHR As ChartObject
Dim MyArray(1 To 7, 0 To 3) As String
Dim i As Integer
For i = LBound(MyArray) To UBound(MyArray)
'Set Values - possibly with named ranges
Dim vArray() As Variant
Dim strNamedRange As String
strNamedRange = "Chart" & i
Set rng = Worksheets("Sheet1").Range(strNamedRange)
vArray = rng
Dim j As Integer
For j = LBound(MyArray, 2) To UBound(MyArray, 2)
MyArray(i, j) = vArray(1, j + 1)
Debug.Print MyArray(i, j)
Next j
Next i
For i = LBound(MyArray) To UBound(MyArray)
With ActiveSheet
Set rng = .Range(MyArray(i, 1)) '1 represents the data range
Set cht = .Shapes.AddChart
cht.Chart.SetSourceData Source:=rng, PlotBy:=xlRows
cht.Chart.ChartType = xlColumnStacked
.ChartObjects(i).Top = .Range(MyArray(i, 2)).Top '0 represents the chart name
.ChartObjects(i).Left = .Range(MyArray(i, 2)).Left '2 represents the cell identifying the chart location
.ChartObjects(i).Activate
With ActiveChart
.Axes(xlValue).Select
.Axes(xlValue).Delete
.HasTitle = True
.ChartTitle.Text = ActiveSheet.Range(MyArray(i, 3)).Text '3 represents the cell where the title text is located
End With
End With
Next i
End Sub
Do that, run the sub and it will create 7 charts as described in the table - using a loop.

Resources