Цикл VBA с пустыми указателями - PullRequest
0 голосов
/ 08 ноября 2019

Мне нужно рисовать диаграмму каждые два столбца, у меня 30 столбцов, поэтому у меня 15 графиков. Я делаю это с помощью цикла в диапазонах, но в большинстве графиков я не получаю баллов, и только в трех из них яполучить полную диаграмму, остальные пусты Я не знаю, что я делаю неправильно. изображение показывает, что я получаю

Sub loopChart(SheetName, ChartSheet, ChartTop)
' define variables
Dim myRange, newRange As Range
Dim c, r, l As Integer
Dim lRow As Long
Dim lColumn As Long

c = 1
r = 1
l = 0

' range of  each measure

lColumn = Sheets(SheetName).Cells(1, Columns.Count).End(xlToLeft).Column
lRow = Sheets(SheetName).Cells(Rows.Count, 1).End(xlUp).Row

'loop for each range of the data
While c < lColumn
'set data source for the next chart
    With Worksheets(SheetName)

        Set myRange = .Range(.Cells(1, c), .Cells(lRow, c + 1))


        For Each cell In myRange
            If cell.Value = "" Or cell.Offset(1, 0).Value = "" Then
                r = cell.Row
        Exit For
    End If
 Next

    Set newRange = .Range(.Cells(1, c), .Cells(r - 1, c + 1))

End With

'create chart
Sheets(ChartSheet).Select
    ActiveSheet.Shapes.AddChart.Select

    With ActiveChart

        '.Axes(xlValue)
        .ChartType = xlXYScatter 'xlLine
        .SetSourceData Source:=newRange, PlotBy:=xlColumns  'sets source data for graph including labels

        .SetElement (msoElementLegendRight)  'including legend
        .HasTitle = True
        'dimentions & location:

        .Parent.Top = ChartTop
        .Parent.Left = c * 200  'defines the coordinates for the left side of the chart
        .Parent.Height = 300
        .Parent.Width = 400
        .ChartTitle.Text = SheetName & " " & (c - l) ' name of the chart from the column of each range



    End With

c = c + 2
l = l + 1
Wend
End Sub

1 Ответ

1 голос
/ 14 ноября 2019
lColumn = Sheets(SheetName).Cells(1, Columns.Count).End(xlToLeft).Column
lRow = Sheets(SheetName).Cells(Rows.Count, 1).End(xlUp).Row
fBlank = lRow + 1

While c < lColumn
'set data source for the next chart
    With Worksheets(SheetName)

        Set myRange = .Range(.Cells(1, c), .Cells(fBlank, c + 1))

        For Each cell In myRange
         If cell.Value = cell.Offset(0, 1).Value Then
                r = cell.Row
        Exit For
    End If
 Next

    Set newRange = .Range(.Cells(1, c), .Cells(r - 1, c + 1))

End With
...