如何在现有的VBA图表中添加新的水平(极限线)系列

时间:2019-01-31 01:17:09

标签: excel vba

我可以成功创建数据透视图(条形图),但现在想添加水平的上限和下限线。我研究并阅读了多个站点,但在SeriesCollection.NewLines上不断收到相同的错误。错误是

  

“对象变量或未设置块变量”。

这让我发疯了!

我正在使用Microsoft Office 365 ProPlus。

'Create Pivot Chart button:  Creates Pivot chart on Main and PivotTable tabs.
Private Sub CommandButton7_Click()
    Dim sh As Shape
    Dim ws As Worksheet
    Dim ch As Chart
    Dim pt As PivotTable
    Dim TitleText As String
    Dim Sheet3 As Worksheet
    Dim product As String
    Dim wb As Workbook
    Dim d As Double
    Dim points As Long
    Dim i As Long
    Dim ul As Variant
    Dim ch1 As ChartObject
    Dim sName As String
    Dim s As Series

    Set Sheet3 = Sheets("FilteredData")
    Set ws = Worksheets("PivotTable")

    If (LChart = True) Or (FFTChart = True) Then
      Set sh = ws.Shapes.AddChart2(XlChartType:=XlChartType.xlLine, Width:=903, Height:=398)
    Else
      Set sh = ws.Shapes.AddChart2(XlChartType:=XlChartType.xlColumnClustered, Width:=903, Height:=398)
    End If

    Set ch = sh.Chart
    Set pt = ws.PivotTables("PivotTable")
    product = Range("D4")  'Used for Chart title.  User entered
    ch.SetSourceData pt.TableRange1
    sh.Top = pt.TableRange1.Top
    sh.Left = pt.TableRange1.Left + pt.TableRange1.Width + 10

    ch.Axes(xlValue, xlPrimary).HasTitle = True
    ch.Axes(xlValue, xlPrimary).AxisTitle.Characters.Text = SelectedUnit
    ch.Axes(xlValue, xlPrimary).AxisTitle.Font.Bold = True
    ch.Axes(xlValue, xlPrimary).AxisTitle.Font.Size = 12
    ch.ChartArea.Border.LineStyle = xlSolid

    If (LChart = True) Then
     ch.Axes(xlCategory, xlPrimary).HasMajorGridlines = False
    Else
      ch.Axes(xlCategory, xlPrimary).HasMajorGridlines = True
    End If

    ch.HasTitle = True
    TitleText = ws.Range("B4")
    ch.ChartTitle.Font.Bold = True
    ch.ChartTitle.Text = TitleText & " " & "(" & SelectedMeas & ")" & Chr(10) & "(" & product & ")"
    ch.HasLegend = True

    d = 22  'Use as upper limit (ul)
    points = Sheet3.Cells(Sheet3.Rows.Count, 1).End(xlUp).Row - 1
    ReDim ul(0 To 0)

    For i = 0 To points - 1
      ul(i) = d
      If i <> points - 1 Then ReDim Preserve ul(0 To i + 1)
    Next i

   Worksheets("PivotTable").Activate  'worked
   ActiveSheet.ChartObjects("Chart 1").Activate  'worked

   **Set s = ch1.Chart.SeriesCollection.NewLines** 'ERROR - Run-time'91'  Object variable or With block variable not set
   sName = "Upper Limit"
   With s
     .Name = sName
     .Values = ul
   End With

0 个答案:

没有答案