Abdullah Khan
Abdullah Khan

Reputation: 21

Adding Annual Segmentation to Line Chart with VBA

I am creating multiple time series graphs for each row of my table (State Level Monthly Time Series Data). I want these graphs to contain multiple series segmented by year (2018,2019,2020...2023). To answer this segmentation problem, I created a row that pulls the year from each date column. Is there code I can write, perhaps using conditional logic, that provides me with series by year for each graph created for each row? This is what I attempted, but I feel like I am way off. Struggling to format the axis properly as well. Completely new to VBA, any help very appreciated.

Sub CreateGraphsForRow()
    Dim wb As Workbook
    Dim ws As Worksheet
    Dim rngData As Range
    Dim lastRow As Long
    Dim lastCol As Long
    Dim rowIndex As Long
    Dim seriesRange As Range
    Dim cht As ChartObject
    
    ' Set the workbook and worksheet where your data is located
    Set wb = Workbooks("State_30@3_Trends.xlsx") ' Change the workbook name as needed
    Set ws = wb.Worksheets("UNS 30@3") ' Change the worksheet name as needed
    
    ' Define the range of your data
    With ws
        lastRow = .Cells(.Rows.Count, "G").End(xlUp).Row
        lastCol = .Cells(149, .Columns.Count).End(xlToLeft).Column
        Set rngData = .Range("G149", .Cells(lastRow, lastCol))
    End With
    
    ' Loop through each row in the data range
    For rowIndex = 1 To rngData.Rows.Count
        ' Create a new chart object on the worksheet
        Set cht = ws.ChartObjects.Add(Left:=10, Width:=375, Top:=75 + (rowIndex - 1) * 250, Height:=225)
        
        ' Define the range for the graph's data series
        Set seriesRange = rngData.Rows(rowIndex)
        
        ' Set the chart's data source to the defined range
        cht.Chart.SetSourceData Source:=seriesRange
        
        ' Set the chart type to Line
        cht.Chart.ChartType = xlLine
        
        ' Set other optional properties of the chart, such as chart title, axis labels, etc.
        cht.Chart.HasTitle = True
        cht.Chart.ChartTitle.Text = "Graph Title"
        ' Customize other properties as needed
        
    Next rowIndex
End Sub

Upvotes: 0

Views: 39

Answers (0)

Related Questions