Andy G Andy G - 11 months ago 121
MySQL Question

Excel VBA - Selecting multiple table columns for purposes of chart data

I am writing a macro that creates a simple chart based on data from an excel table. I would like to be able to select the from 5 different columns on my table. Those columns are named as followed:

"Calendar date" <-- I would like this to be my x-axis

"AHT", "Target AHT" <-- These would be my primary y-axis

"Transfer", "Target Transfers" <-- Secondary y-axis

I am unsure how to select multiple table columns for my chart data. I can only get it to work if I select 1 single column, and vba doesn't appear to work the same way as it would for a range obj (i.e., range("A:B, D:D, F:G")).

EDIT: The columns in my table that I need to use are 2 and 9:12

Sub myChart()

Dim myChart As Chart, cht As ChartObject
Dim rngChart As Range, destSht As String

destSht = ActiveSheet.Name
Set myChart = Charts.Add
Set myChart = myChart.Location(where:=xlLocationAsObject, Name:=destSht)

*****My issue is with selecting multiple table columns below*****
myChart.SetSourceData Source:=ActiveSheet.ListObjects("Table1").ListColumns(2), PlotBy:=xlColumns
myChart.ChartType = xlColumnClustered


Set cht = ActiveChart.Parent
Set rngChart = Range("A1100:K1115")

cht.Left = rngChart.Left
cht.Top = rngChart.Top
cht.Width = rngChart.Width
cht.Height = rngChart.Height


End Sub


Include code like this:

Dim rngData As Range

With ActiveSheet.ListObjects("Table1").DataBodyRange
    Set rngData = Union(.Columns(2), .Columns(9), Columns(10), _
        .Columns(11), .Columns(12))
End With

myChart.SetSourceData Source:=rngData, PlotBy:=xlColumns