简体   繁体   中英

Variable Range in Excel VBA

I am trying to draw line graphs in Excel.

I have the x-axis as a constant range but I am trying to make the Y-axis a variable range. My data is is B2-F2, B3-F3, B4-F4, B5-F5, B6-F6, B7-F7. I want to plot each of these as the Y-axis with my constant X-axis range but cannot figure out how to get the Y-axis data to be variable.

I get 6 graphs with B2-F2 as the Y-axis.

This is what I have so far:

Dim rowno As Integer
Dim colno As Range
Dim time As Range
Dim pressure As Range
Dim Startrow As Integer
Dim Lastrow As Integer

Startrow = 2
Lastrow = 7

Set time = Range("B1:F1")

' THIS LINE HERE IS THE LINE IM STRUGGLING WITH
Set pressure = "B"&Startrow&":"&"F"&Lastrow

ActiveSheet.Shapes.AddChart.Select
ActiveChart.ChartType = xlLine
ActiveChart.SeriesCollection.NewSeries
ActiveChart.SeriesCollection(1).XValues = time
ActiveChart.SeriesCollection(1).Values = pressure

You have to use a loop. Something like this should get you close:

Sub test()

  Dim rowno As Integer
  Dim colno As Range
  Dim time As Range
  Dim pressure As Range
  Dim Startrow As Integer
  Dim Lastrow As Integer
  Dim i As Long

  Startrow = 2
  Lastrow = 7

  Set time = Range("B1:F1")
  For i = 2 To 7

   Set pressure = Range("B" & i & ":F" & i)

    ActiveSheet.Shapes.AddChart.Select
    ActiveChart.ChartType = xlLine
    ActiveChart.SeriesCollection.NewSeries
    ActiveChart.SeriesCollection(1).XValues = time
    ActiveChart.SeriesCollection(1).Values = pressure

  Next i

End Sub

I don't think the graphs part is quite right, so hopefully you'll be able to tweak that to get your expected results, but this will at least solve your immediate problem of the Y axis not updating.

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