我在尝试设置图表的 plotarea.width 属性的子例程中遇到错误。
如果我注释掉前面的行,其他维度也会导致此错误。没有ActiveChart,没有选择等。具体的错误信息是这样的:“-2147467259 (80004005) Method 'Width' of object 'PlotArea' failed”
这让我很困惑,原因有几个:
- 在调试模式下,F8 单步执行代码不会发生错误。
- AFAIK“宽度”不是“方法”,而是图表绘图区域的“属性”,因此即使错误消息也相当模糊。
有什么想法吗?这是我可以分享的尽可能多的代码,完整的 ChartSizeMedium 子例程,以及一个虚拟片段,向您展示我如何建立图表并将其传递给在传递给另一个函数之前设置大小和其他一些属性的子程序将系列数据添加到图表中。
Option Explicit
Private Sub EstablishChartObject()
Dim cObj as ChartObject
Set cObj = ActiveSheet.ChartObjects.Add(Left:=30, Top:30, Width:=740, Height:=300)
ChartSizeMedium cObj.Chart, "Integer", "Example Chart Title"
End Sub
Private Sub ChartSizeMedium(cht As Chart, NumType As String, Optional chtTitle As String)
'Subroutine to make a consistent size chart
Dim s As Long
With cht
'Add a chart title if one exists.
If Len(chtTitle) > 0 Then
.HasTitle = True
.chartTitle.Characters.Text = chtTitle
End If
'Create the default chart Legend
.HasLegend = True
With .Legend
.Position = xlTop
.Font.Size = 11
.Font.Bold = True
End With
'Format the axes
.Axes(xlValue).MajorGridlines.Format.Line.Visible = msoFalse
.Axes(xlValue).MinorGridlines.Format.Line.Visible = msoFalse
'Format the size of the chart
With .Parent
.Width = 740
.Height = 396
End With
With .PlotArea
.Width = 640 '<---- THIS LINE TRIGGERS THE ERROR
.Height = 280
.Left = 30
.Top = 30
End With
End With
'Some charts start with more than one series container, so make sure they're gone:
With cht
Do Until .SeriesCollection.Count = 0
s = .SeriesCollection.Count
.SeriesCollection(s).Delete
Loop
End With
End Sub
2012 年 12 月 12 日更新
我删除了所有无问题的代码并仅使用带有块的 PlotArea,在同一例程中,我还尝试设置图表类型(几个值),如本示例所示,在尝试设置之前手动添加一系列数据PlotArea 尺寸,但错误仍然存在:
Option Explicit
Private Sub EstablishChartObject2()
Dim cObj As ChartObject
Dim sh As Worksheet
Set sh = ActiveSheet
Dim srs As Series
Set cObj = sh.ChartObjects.Add(Left:=30, Top:=30, Width:=740, Height:=300)
Set srs = cObj.Chart.SeriesCollection.NewSeries
srs.Values = "={1,3,5,7,4}"
cObj.Chart.ChartType = 57
With cObj.Chart.PlotArea
.Width = 100 '<---- THIS LINE TRIGGERS THE ERROR
.Height = 280
.Left = 30
.Top = 30
End With
End Sub