图表标题莫名其妙地消失

我有一个macros在给定工作簿中的每个选项卡上创build图表(在做其他事情之后)。 作为其中的一部分,图表应该有一个标题添加,标题设置为工作表名称。 下面是我试图做到这一点:

S.Shapes.AddChart2(227, xlLine).Select ActiveChart.SeriesCollection.NewSeries ActiveChart.FullSeriesCollection(1).Name = "=" & S.Name & "!$H$1" ActiveChart.FullSeriesCollection(1).Values = "=" & S.Name & "!$H$2:$H$" & i ActiveChart.FullSeriesCollection(1).XValues = "=" & S.Name & "!$G$2:$G$" & i temp = 0 Do While ActiveChart.HasTitle = False If temp <= 5 Then ActiveChart.HasTitle = True temp = temp + 1 Else MsgBox "The script failed to add a title to the chart on " & S.Name End If Loop If ActiveChart.HasTitle Then ActiveChart.ChartTitle.Text = S.Name End If 

对于上下文,我是该表的最后一行数据(根据该表上的数据点的数量dynamic设置),S是保存当前表的工作表variables,temp只是一个用于防止的通用计数器一个无限循环。

真正让我感到的是,错误发生在上面代码片段的倒数第二行。 为了macros观,甚至到了那里,必须有一个图表标题。 但是,那么抛出的错误说没有一个。

如果我每次遍历上面的代码都不会发生错误,但是重新启动屏幕更新并激活S并不能防止错误。

所以看起来好像有一些上下文没有被正确的代码处理,但我无法弄清楚我错过了什么。

谢谢你的帮助

我需要特定的错误,但我有怪异的select/活动对象的怪癖。 如果这是对图表的引用,那么你应该能够用“S”replace这些ActiveChart引用。 根据您的Excel版本,它可能是S.Chart.SeriesCollection …

有些东西要testing,看“这一行

 Dim cht as Chart Set cht = S.Shapes.AddChart2(227, xlLine).Chart cht.SetElement (msoElementChartTitleAboveChart) 'this line cht.SeriesCollection.NewSeries cht.FullSeriesCollection(1).Name = "=" & S.Name & "!$H$1" cht.FullSeriesCollection(1).Values = "=" & S.Name & "!$H$2:$H$" & i cht.FullSeriesCollection(1).XValues = "=" & S.Name & "!$G$2:$G$" & i temp = 0 Do While cht.HasTitle = False If temp <= 5 Then cht.HasTitle = True temp = temp + 1 Else MsgBox "The script failed to add a title to the chart on " & S.Name End If Loop If cht.HasTitle Then cht.ChartTitle.Text = S.Name End If 

从这里采取

我最终去的代码如下。 所有的信贷给吉米·史密斯和大卫·泽曼斯,但他们让我在这里,只是想捕捉结束的状态,谁发现这个网页的未来

 Dim ch as ChartObject Set ch = S.ChartObjects.Add(Left:=Range("J2").Left, Top:=Range("J2").Top, Width:=500, Height:=325) ch.Chart.SeriesCollection.NewSeries ch.Chart.FullSeriesCollection(1).Name = "=" & S.Name & "!$H$1" ch.Chart.FullSeriesCollection(1).Values = "=" & S.Name & "!$H$2:$H$" & i ch.Chart.FullSeriesCollection(1).XValues = "=" & S.Name & "!$G$2:$G$" & i ch.Chart.ChartType = xlLine temp = 0 Do While ch.Chart.HasTitle = False If temp <= 5 Then ch.Chart.HasTitle = True temp = temp + 1 Else MsgBox "The script failed to add a title to the chart on " & S.Name End If Loop If ch.Chart.HasTitle Then ch.Chart.ChartTitle.Text = S.Name End If