VBA Code to Create a Custom Chart using Excel Chart Objects

VBA Code:

Sub CreateCustomChart()
    Dim chartWorksheet As Worksheet
    Dim chartObject As ChartObject
    Dim dataRange As Range
    Dim chartRange As Range
    Dim chart As Chart
    
    ' Set the chart worksheet where the chart will be created
    Set chartWorksheet = ThisWorkbook.Sheets("Chart Sheet") ' Change the sheet name as desired
    
    ' Set the data range for the chart
    Set dataRange = Worksheets("Data Sheet").Range("A1:B10") ' Change the sheet name and range as desired
    
    ' Set the chart range including the headers
    Set chartRange = chartWorksheet.Range("A1:C11")
    
    ' Create a new chart object on the chart worksheet
    Set chartObject = chartWorksheet.ChartObjects.Add(Left:=10, Top:=10, Width:=400, Height:=300)
    
    ' Set the chart object properties
    With chartObject
        .Chart.ChartType = xlLine
        .Chart.SetSourceData Source:=dataRange
        .Chart.HasTitle = True
        .Chart.ChartTitle.Text = "Custom Chart"
    End With
    
    ' Move the chart object to the desired position on the chart worksheet
    chartObject.Top = 100
    chartObject.Left = 100
    
    ' Copy the chart object to a separate chart sheet
    Set chart = chartObject.Chart
    chart.ChartArea.Copy
    Sheets.Add(After:=Sheets(Sheets.Count)).Select
    ActiveSheet.Paste
    
    ' Inform the user that the custom chart has been created
    MsgBox "The custom chart has been created."
End Sub

Check All VBA Codes

Join Our Telegram Group techguruplus telegram group Join Our WhatsApp Group techguruplus whatsapp group

Leave a Comment