简体   繁体   中英

VBA function to dynamically adapt chart data range

I am quite new with using VBA, especially to format chart on Excel but already run into an issue. I am trying to generate a Graph but the rows of the reference cells will vary depending on the data available.

Right now, my data are in the range AE741:AG762 but in the next iteration the row might be different. Can you help me write a code that dynamically adapt the chart data range depending on my data available? What I have at hand is the row reference (ie for each iteration I know where my data start and end, in the present case 741 to 762). I also have the range adresse reported in another cell, such that in my case cell Y10 takes the value AE741:AG762.

I guess the only thing I need (but did not manage to do) is to call this range value into my VBA function.

Chart_Test Macro
Set myRange = Workbook().Worksheet(3).Cell(25, 10).Value
ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.SetSourceData Source:=Range("AE741:AG762")
ActiveChart.SeriesCollection(2).Select
ActiveChart.SeriesCollection(2).AxisGroup = 2
ActiveChart.SeriesCollection(2).Select
ActiveChart.Legend.Select
Selection.Delete
ActiveChart.Axes(xlCategory).Select
ActiveChart.SeriesCollection(2).Select
ActiveChart.SeriesCollection(2).ChartType = xlColumnClustered
ActiveChart.SeriesCollection(2).Select
With Selection.Format.Fill
    .Visible = msoTrue
    .ForeColor.ObjectThemeColor = msoThemeColorAccent6
    .ForeColor.TintAndShade = 0
    .ForeColor.Brightness = -0.25
    .Transparency = 0
    .Solid
End With
ActiveChart.SeriesCollection(1).Select
With Selection.Format.Line
    .Visible = msoTrue
    .ForeColor.RGB = RGB(0, 176, 240)
    .Transparency = 0
End With
End Sub

Thanks for the much appreciated help! Benjamin

Change these lines:

Set myRange = Workbook().Worksheet(3).Cell(25, 10)
ActiveChart.SetSourceData Source:=Range("AE741:AG762")

To these ones:

Dim myRange As Range 'myRange must be declared as Range
'Ensure that "ThisWorkbook" is alright for you, meaning that you are running this code 
'from the Workbook containing the value you want at cell(25,10)
Set myRange = ThisWorkbook.Worksheets(3).Cell(25, 10) '.Cell(25, 10) Or .Range("Y10")
ActiveChart.SetSourceData Source:=Range(myRange.Address)
'Or simply
ActiveChart.SetSourceData Source:=myRange

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM