对象variables或块variables未设置(错误91)错误

我有以下工作更早的代码,但现在显示一个错误:

Sub AttachLabelsToPoints() 'Dimension variables. Dim Counter As Integer Dim ChartName As String Dim xVals As String ' Disable screen updating while the subroutine is run. Application.ScreenUpdating = False 'Store the formula for the first series in "xVals". xVals = ActiveChart.SeriesCollection(1).Formula 'Extract the range for the data from xVals. xVals = Mid(xVals, InStr(InStr(xVals, ","), xVals, _ Mid(Left(xVals, InStr(xVals, "!") - 1), 9))) xVals = Left(xVals, InStr(InStr(xVals, "!"), xVals, ",") - 1) Do While Left(xVals, 1) = "," xVals = Mid(xVals, 2) Loop 'Attach a label to each data point in the chart. For Counter = 1 To Range(xVals).Cells.Count ActiveChart.SeriesCollection(1).Points(Counter).HasDataLabel = _ True ActiveChart.SeriesCollection(1).Points(Counter).DataLabel.Text = _ Range(xVals).Cells(Counter, 1).Offset(0, -1).Value Next Counter End Sub 

该错误是专门围绕xVals = ActiveChart.SeriesCollection(1).Formula语句。 当我把它放在它的前面,它只是要求一个对象。

任何人都可以帮助我什么是错的?

确保您要使用的图表在工作表上处于活动状态的实际图表。

在设置“xVals”之前放置此代码并根据需要进行调整。

 Dim c As ChartObject Set c = Sheets("Sheet6").ChartObjects("Chart 1") 'change to your chart name c.Activate 'Store the formula for the first series in "xVals". xVals = ActiveChart.SeriesCollection(1).Formula 

一般来说,使用任何Active (Chart / Sheet / Cell / etc.)是不好的做法,但是在操作图表时,这是AFAIK的唯一方法。 我不知道用这种方法直接处理对象的方法。 如果有人这样做,也许他们可以发表更好的答案。