我是VBA的新手。我已经在工作表1中创建了一个柱形图,并希望将其移到工作表2中。
我正在尝试使用工作表索引作为参考,而不是特定名称。
我想出了一些代码,以activesheet.chartobjects.select
(最后一行的第六行)开头的部分是问题开始的地方...
请帮助,我非常感谢您的帮助和友善。
Option Explicit
Sub createClusteredBarChart()
Dim myworksheet As Worksheet
Dim mysourcedata As Range
Dim mychart As Chart
Dim mychartdestination As Range
Set myworksheet = ThisWorkbook.Worksheets("sales figures")
With myworksheet
Set mysourcedata = .Range("a1:f6")
Set mychartdestination = .Range("A2:z10")
Set mychart = .Shapes.AddChart(XlChartType:=xlColumnClustered, _
Left:=mychartdestination.Cells(1).Left, Top:=mychartdestination.Cells(1).Top, _
Width:=mychartdestination.Width, Height:=mychartdestination.Height).Chart
With mychart
.Axes(xlValue).MaximumScale = 16000000
.Axes(xlValue).MajorUnit = 4000000
.ChartArea.Select
.ChartArea.Height = 216
.ChartArea.Width = 360
.ChartGroups(1).GapWidth = 65
End With
ActiveSheet.ChartObjects.Select
ActiveSheet.ChartObjects.Copy
Sheets("Sheet18").Range("a1").Paste
End With
mychart.SetSourceData Source:=mysourcedata
End Sub
答案 0 :(得分:1)
尝试此代码
备注:
Option Explicit
Sub createClusteredBarChart()
' Declare objects
Dim myworksheet As Worksheet
Dim mysourcedata As Range
Dim mychart As Chart
Dim mychartdestination As Range
' Set source worksheet
Set myworksheet = ThisWorkbook.Worksheets("sales figures")
With myworksheet
' Set source data
Set mysourcedata = .Range("a1:f6")
' Set destination range
Set mychartdestination = .Range("A2:z10")
' Create blank chart
Set mychart = .Shapes.AddChart(XlChartType:=xlColumnClustered, _
Left:=mychartdestination.Cells(1).Left, Top:=mychartdestination.Cells(1).Top, _
Width:=mychartdestination.Width, Height:=mychartdestination.Height).Chart
End With
' Adjust chart's settings
With mychart
.Axes(xlValue).MaximumScale = 16000000
.Axes(xlValue).MajorUnit = 4000000
.ChartArea.Select
.ChartArea.Height = 216
.ChartArea.Width = 360
.ChartGroups(1).GapWidth = 65
' Set chart's source data
.SetSourceData Source:=mysourcedata
End With
' This line will move the chart to another worksheet (in this example sheet index = 2) (be careful when you have hidden sheets)
mychart.Location xlLocationAsObject, ThisWorkbook.Worksheets(2).Name
End Sub
答案 1 :(得分:0)
工作表中嵌入的图表对象不支持Copy方法,仅图表表(保存在其自己的工作表中)不支持Copy方法。您必须将其复制为形状
因此替换
ActiveSheet.ChartObjects.Select
ActiveSheet.ChartObjects.Copy
Sheets("Sheet18").Range("a1").Paste
使用
myworksheet.shapes(1).copy 'assuming it's the only object on the sheet
Sheets("Sheet18").Range("a1").PasteSpecial