QP School

Full Version: Create a chart from data with VBA
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Example:

Sub CreateChart()
    Dim chartSheet As Worksheet
    Dim dataSheet As Worksheet
    Dim chartObj As ChartObject
    Dim chartRange As Range

    'Set the data sheet where the chart data is located
    Set dataSheet = ThisWorkbook.Sheets("Sheet1")

    'Set the range of data for the chart (adjust the range as per your data)
    Set chartRange = dataSheet.Range("A1:B5")

    'Create a new worksheet to place the chart
    Set chartSheet = ThisWorkbook.Sheets.Add

    'Create the chart as a column chart on the new worksheet
    Set chartObj = chartSheet.ChartObjects.Add(Left:=50, Width:=375, Top:=75, Height:=225)
    With chartObj.Chart
        .SetSourceData Source:=chartRange
        .ChartType = xlColumnClustered
    End With
End Sub

Explanation:

The code defines a subroutine named CreateChart.
It declares variables for the chart sheet (chartSheet), data sheet (dataSheet), chart object (chartObj), and chart data range (chartRange).
Set dataSheet = ThisWorkbook.Sheets("Sheet1") specifies the worksheet ("Sheet1") where the chart data is located.
Set chartRange = dataSheet.Range("A1:B5") sets the range of data for the chart (adjust the range as per your data).
A new worksheet (chartSheet) is created to place the chart using ThisWorkbook.Sheets.Add.
The chart is created as a column chart on the new worksheet using chartSheet.ChartObjects.Add. 
The chart dimensions and position are adjusted using the Left, Width, Top, and Height parameters.
The chart source data is set to chartRange using .SetSourceData Source:=chartRange.
The chart type is set to a clustered column chart using .ChartType = xlColumnClustered.