我相信这个会非常快。
我已经编写了一个代码,如果选择了某个切片器项,则允许将趋势线添加到图表中。但是,我想根据条件包括添加和删除趋势线(如果选择,删除和相反)。
当代码分成2个子代码时代码工作,但是当我包含&修改它没有。
如果语句: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
任何人都可以帮我找到解决方案并给出一个简短的解释(作为我学习的一部分)为什么会这样?我很感激:))
答案 0 :(得分:0)
感谢John Coleman的回答,代码现在可以运行了,这是解决方案: Sub 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