我相信这会很快。如果选择了某些切片器项目,我编写了一个代码,允许将趋势线添加到图表中。但是,我希望根据条件同时包含添加和删除趋势线(如果选择,删除和相反)。代码在分成 2 个子部分时有效,但当我包含和修改它时无效。代码失败 if 语句: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
谁能帮我找到解决方案并简要解释(作为我学习的一部分)为什么会发生这种情况?我将不胜感激 :)