Search code examples
excelvbaexcel-2010excel-chartsexcel-tables

How to Set Range of Table Data for use with Chart


Using Excel 2010 I am trying to create a chart on Sheet1 using partial data from several different tables. In the below example I am just trying to pull the data from one table as a start. I seem to be having difficulty setting the range of this data in this table.

I will eventually loop through about 8 data columns of various lengths per table with approx. 21 tables. So any help automating this would be great

This is what I have so far...

Sub createChart()
    Dim rng As Range
    Dim chrt As Object

    'Table is named BMS_01_01_Module_01 and the column Name I want data from is Cell 1 Voltage
    Set chrt = Sheet1.Shapes.AddChart2
    chrt.ChartArea.SetSourceData Source:=activesheetlistobjects("BMS_01_01_Module_01").ListColumns("Cell 1 Voltage").Range
    chrt.ChartArea.ChartType = x1Line
End Sub

Solution

  • I ended up making some changes to my code. I just wish there was a way to reference the table without having to activate the sheet the table is in first. Note: the Chart and Tables are not on the same sheets.

    This is what ended up working for a single range:

    Sub createChart()
    Dim rng As Range
    Dim cht As Object
    Dim Ws As Worksheet
    
    Set cht = Sheet1.Shapes.addChart
    
    Worksheets("BMS_01_Module_01").Activate
    Set Ws = ActiveSheet
    
    Ws.ListObjects("BMS_01_Module_01").ListColumns("Cell 1 Voltage").Range.Select
    cht.Chart.SetSourceData Source:=Selection
    cht.Chart.ChartType = xlLine
    
    
    End Sub