Justin Smudz
Justin Smudz

Reputation: 1

Adding a new series (Line) to preexisting chart (Stacked Bar)

I am trying to add a new series that plots the cumulative sum of hours on a monthly basis on a secondary axis. The stacked bar chart (which tracks monthly hours spent per category) is working and fully functional. I'm getting an error, "Application-defined or object-defined error" for the line: Set ns = chart.SeriesCollection.NewSeries and I cannot figure out why. I'm new to this, so feedback or advice is appreciated!

Sub CreateCombinationChartFromPivotTable()

Dim ws As Worksheet
Dim pt As pivotTable
Dim chartObj As ChartObject
Dim chart As chart
Dim lastRow As Long
Dim monthRange As Range
Dim technicalAreasRange As Range
Dim totalHoursRange As Range
Dim cumulativeValues() As Double
Dim i As Long
Dim totalHours As Double

' Set the worksheet and pivot table objects
Set ws = ThisWorkbook.Sheets("Sheet1") ' Change this to your sheet name
Set pt = ws.PivotTables("PivotTable5") ' Change this to your pivot table name

' Get the data range of the PivotTable (assuming it's fully populated)
lastRow = pt.TableRange2.Rows.Count
Set monthRange = pt.TableRange2.Columns(1) ' First column: Month and Year

' Columns from 2 to last - 1: Technical Areas (for stacked bars)
Set technicalAreasRange = pt.TableRange2.Columns(2).Resize(, pt.TableRange2.Columns.Count - 2)

' Last column: Total Hours (to calculate the cumulative sum)
Set totalHoursRange = pt.TableRange2.Columns(pt.TableRange2.Columns.Count)

' Initialize the cumulative values array
ReDim cumulativeValues(1 To lastRow)

' Add a new chart to the sheet
Set chartObj = ws.ChartObjects.Add(Left:=100, Width:=600, Top:=100, Height:=400)
Set chart = chartObj.chart

' Set the chart type for the stacked bar chart
chart.ChartType = xlColumnStacked
chart.SetSourceData Source:=technicalAreasRange ' Use the technical areas for stacked bars

' Calculate cumulative total hours for each month
cumulativeValues(1) = 0 ' Initialize first cumulative value as zero (or the first value if needed)

For i = 2 To lastRow
    ' Ensure the Total Hours cell contains numeric data before adding
    If IsNumeric(totalHoursRange.Cells(i, 1).Value) Then
        totalHours = totalHoursRange.Cells(i, 1).Value
    Else
        totalHours = 0 ' Set to 0 if the value is not numeric
    End If
    
    cumulativeValues(i) = cumulativeValues(i - 1) + totalHours
Next i

' Add the new series for the cumulative line (total hours)
Set ns = chart.SeriesCollection.NewSeries
With ns
    .XValues = monthRange
    .Values = cumulativeValues
    .ChartType = xlLine
    .AxisGroup = xlSecondary
    .Name = "Cumulative Hours"
End With

' Format the chart
chart.HasTitle = True
chart.ChartTitle.Text = "Hours Spent per Month (Stacked Bar + Cumulative Line)"
chart.Axes(xlCategory, xlPrimary).CategoryNames = monthRange ' Set the category names to the months
chart.Axes(xlValue, xlPrimary).HasTitle = True
chart.Axes(xlValue, xlPrimary).AxisTitle.Text = "Hours by Technical Area"
chart.Axes(xlValue, xlSecondary).HasTitle = True
chart.Axes(xlValue, xlSecondary).AxisTitle.Text = "Cumulative Hours"

' Adjust the chart to fit well on the page
chartObj.Width = 800
chartObj.Height = 500

' Optional: Move and resize the chart for better visualization
chartObj.Left = 150
chartObj.Top = 50

End Sub

Upvotes: 0

Views: 32

Answers (0)

Related Questions