VBA Activechart.CopyPicture对象定义的错误

我在使用Excel创build和复制VB6中的图表时遇到问题。 我有以下代码

Private Sub CreateChart(Optional ByVal ChartTitle As String _ , Optional ByVal xAxis As Excel.Range _ , Optional ByVal yAxis As Excel.Range _ , Optional ByVal ColumnName As String _ , Optional ByVal LegendPosition As XlLegendPosition = xlLegendPositionRight _ , Optional ByVal rowIndex As Long = 2 _ , Optional ByRef ChartType As String = xlLineMarkers _ , Optional ByVal PlotAreaColorIndex As Long = 2 _ , Optional ByVal isSetLegend As Boolean = False _ , Optional ByVal isSetLegendStyle As Boolean = False _ , Optional ByVal LegendStyleValue As Long = 1) Const constChartLeft = 64 Const constChartHeight = 300 Const constChartWidth = 700 Dim xlChart As Excel.ChartObject Dim seriesCount As Long Dim ColorIndex As Long Dim marrayhold() As Variant Dim counter As Long Dim j As Long With mWorksheet .Rows(rowIndex).RowHeight = constChartHeight Set xlChart = .ChartObjects.Add(.Rows(rowIndex).Left, .Rows(rowIndex).Top, constChartWidth, constChartHeight) End With With xlChart.chart .ChartType = ChartType .SetSourceData Source:=yAxis, PlotBy:=xlRows .SeriesCollection(1).XValues = xAxis .HasTitle = True .Legend.Position = LegendPosition .Legend.Font.Size = 7.3 .Legend.Font.Bold = True .Legend.Border.LineStyle = xlNone .Legend.Border.ColorIndex = 1 .ChartTitle.Characters.Text = ChartTitle .ChartTitle.Font.Bold = True .Axes(xlValue).TickLabels.Font.Size = 8 ' yAxis Labels .Axes(xlCategory).TickLabels.Font.Size = 8 ' xAxis Labels .PlotArea.Interior.ColorIndex = PlotAreaColorIndex .PlotArea.Interior.ColorIndex = 15 .PlotArea.Interior.PatternColorIndex = 1 .PlotArea.Interior.Pattern = xlSolid xlChart.Name = "Chart 1" Call Copy_Chart End With End Sub 

有一个复制图表的function,这是错误发生的地方

 Public Function Copy_Chart() With mWorksheet .ChartObjects("Chart 1").Activate ActiveChart.CopyPicture Appearance:=xlScreen, Size:=xlScreen, format:=xlPicture .Paste .ChartObjects("Chart 1").Delete End With End Function 

在行ActiveChart.CopyPicture我得到一个错误消息,说:“应用程序定义或对象定义的错误”,我试图研究,但我似乎无法find一种方法来解决这个错误。

一如既往,你应该避免使用Active*对象。

改成

 With mWorksheet .ChartObjects("Chart 1").Chart.CopyPicture Appearance:=xlScreen, Size:=xlScreen, Format:=xlPicture .Paste .ChartObjects("Chart 1").Delete End With 

请注意,你得到错误的原因可能是因为mWorksheet不活跃

您应该创build对ChartObject的引用,而不是激活并依赖活动ChartObject。

在2013年,没有任何需要激活工作表,但要注意访问图表属性 – 这将需要激活工作表。 请参阅如何使用相同的名称引用图表,但在不同的工作表上?

此外,CopyPicture方法没有名为Size的参数,所以您需要删除Size:=xlScreen

 Public Function Copy_Chart() Dim mWorksheet Set mWorksheet = Sheet1 If Not mWorksheet Is Nothing Then With mWorksheet .Activate Dim cht As ChartObject Set cht = .ChartObjects("Chart 1") cht.CopyPicture Appearance:=xlScreen, Format:=xlPicture .Paste cht.Delete End With End If End Function