0

This is probably a stupid question but I only recently started working with VBA. I want to plot a graph. My problem is selecting the range. At the moment I have 29 rows, but this will constantly be changing. I will always have two columns but the rows of my data set will not be constant. How can I change my range selection to update based on a cell value? I can probably use count to count the number of rows, but I'm not sure how to specify a range based on a cell value

ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("I1:J29")
Gangula
  • 5,193
  • 4
  • 30
  • 59
Angie
  • 7
  • 4
  • Find the last row as show [here](https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-excel-with-vba/11169920#11169920) to construct your range and then use that. – Siddharth Rout Aug 02 '19 at 08:00

2 Answers2

1

You could use the below method:

Option Explicit

Sub test()
    Dim LastRowI As Long, LastRowJ As Long, LastRowMax As Long

    'Change sheet name if needed
    With ThisWorkbook.Worksheets("Sheet1")
        'Find the last of row of column I.
        LastRowI = .Cells(.Rows.Count, "I").End(xlUp).Row
        'Find the last of row of column J.
        LastRowJ = .Cells(.Rows.Count, "J").End(xlUp).Row
        'Find the maximun of LastRowI & LastRowJ in case you missing values
        LastRowMax = Application.Max(LastRowI, LastRowJ)
        'I used .Select to mark the range in order to ensure that you use the correct range
        .Range("I1:J" & LastRowMax).Select            
    End With  
End Sub
Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
Error 1004
  • 7,877
  • 3
  • 23
  • 46
0

Yes, you can count the number of rows and assign that number as a variable.

Dim Num_Rows as Integer

Num_Rows = Application.WorksheetFunction.CountA(Range("J:J"))

ActiveSheet.Shapes.AddChart2(201, xlColumnClustered).Select
ActiveChart.SetSourceData Source:=Range("I1:J" & Num_Rows)
Gangula
  • 5,193
  • 4
  • 30
  • 59