VBA:添加或删除趋势线(如果存在)

VBA: Trendline add or remove (if exists)

我相信这个会很快。 我编写了一段代码,如果选择了某些切片器项目,则允许将趋势线添加到图表中。但是,我想根据条件包括添加和删除趋势线(如果选择,删除和相反)。 该代码在被拆分为 2 个 subs 时有效,但是当我包含并修改它时却没有。 如果语句:If x.Selected Then,代码将失败。不过,我认为问题出在If ActiveChart.SeriesCollection(1).Trendlines(1).Selected。 如果已经有趋势线,如何测试?如果是 - 删除,如果不是 - 添加。就这么简单。

Sub trend_add_remv()

Dim x As Excel.SlicerItem, slicer_x As Excel.SlicerCache

Set slicer_x = ActiveWorkbook.SlicerCaches("Slicer_x")

Application.ScreenUpdating = False

For Each x In slicer_x.SlicerItems

  If x.Selected Then 'This part always fails despite the condition is true
      ActiveSheet.ChartObjects("Chart 1").Activate
          If ActiveChart.SeriesCollection(1).Trendlines(1).Selected Then
             ActiveChart.SeriesCollection(1).Trendlines(1).Delete
             ActiveSheet.ChartObjects("Chart 1").Selected = False
          Else
             With ActiveChart
            .SeriesCollection(x.Value & " - " & "Actual Sales").Select
            .SeriesCollection(x.Value & " - " & "Actual Sales").Trendlines.Add
             End With
             ActiveSheet.ChartObjects("Chart 1").Selected = False
          End If
  End If

  On Error GoTo Message

  Next x
  Exit Sub

  Message:
  MsgBox "No actual sales or not selected in the slicer!"

  Application.ScreenUpdating = True

  End Sub

任何人都可以帮助我找到解决方案并简要解释(作为我学习的一部分)为什么会这样吗?我将不胜感激:)

感谢 John Coleman 的回答,代码现在可以工作了,解决方法如下: 子 trendline_add()

Dim x As Excel.SlicerItem, slicer_x As Excel.SlicerCache

Set slicer_x = ActiveWorkbook.SlicerCaches("Slicer_x")

Application.ScreenUpdating = False

For Each x In slicer_x.SlicerItems

If x.Selected Then
    ActiveSheet.ChartObjects("Chart 1").Activate
        If ActiveChart.SeriesCollection(x.Value & " - " & "Actual _
           Sales").Trendlines.Count > 0 Then
          ActiveChart.SeriesCollection(x.Value & " - " & "Actual _
          Sales").Trendlines(1).Delete
        Else
          ActiveChart.SeriesCollection(x.Value & " - " & "Actual Sales").Select
          ActiveChart.SeriesCollection(x.Value & " - " & "Actual Sales").Trendlines.Add
        End If
End If

On Error GoTo Message

Next x
Exit Sub

Message:
MsgBox "No actual sales or not selected in the slicer"

Application.ScreenUpdating = True

End Sub