所以这样的事情对我有用。CopyCharts 将所有图表从源工作表复制到目标工作表。然后 SetChartRef 将目标中图表的引用设置为我想要的。在这个例子中,我知道哪个图表编号是什么。我想它可以改进,以便它使用图表名称。
此外,由于某种原因,如果我在复制和粘贴之间没有延迟,则会出现运行时错误,因此会出现等待功能。
Sub DeleteEmbeddedCharts(target As String)
Dim wsItem As Worksheet
Dim chtObj As ChartObject
For Each chtObj In ThisWorkbook.Worksheets(target).ChartObjects
chtObj.Delete
Next
End Sub
Sub SetChartRef(target As String)
Dim cht As ChartObject
Dim i As Integer
'i specifies which chart to set its data references
i = 0
For Each cht In ThisWorkbook.Worksheets(target).ChartObjects
If i = 0 Then
cht.Chart.SeriesCollection(1).Values = "=" & target & "!$I$2:$I$12"
cht.Chart.SeriesCollection(2).Values = "=" & target & "!$J$2:$J$12"
ElseIf i = 1 Then
cht.Chart.SeriesCollection(1).Values = "=" & target & "!$I$14:$I$25"
cht.Chart.SeriesCollection(2).Values = "=" & target & "!$J$14:$J$25"
ElseIf i = 2 Then
cht.Chart.SeriesCollection(1).Values = "=" & target & "!$I$26:$I$37"
cht.Chart.SeriesCollection(2).Values = "=" & target & "!$J$26:$J$37"
ElseIf i = 3 Then
cht.Chart.SeriesCollection(1).Values = "=(" & target & "!$H$2," & target & "!$H$14," & target & "!$H$26," & target & "!$H$38)"
cht.Chart.SeriesCollection(1).XValues = "=(" & target & "!$E$2," & target & "!$E$14," & target & "!$E$26," & target & "!$E$38)"
ElseIf i = 4 Then
cht.Chart.SeriesCollection(1).Values = "=(" & target & "!$H$2," & target & "!$H$14," & target & "!$H$26," & target & "!$H$38)"
cht.Chart.SeriesCollection(1).XValues = "=(" & target & "!$E$2," & target & "!$E$14," & target & "!$E$26," & target & "!$E$38)"
ElseIf i = 5 Then
cht.Chart.SeriesCollection(1).Values = "=" & target & "!$I$38:$I$49"
cht.Chart.SeriesCollection(2).Values = "=" & target & "!$J$38:$J$49"
End If
i = i + 1
Next
End Sub
Sub CopyCharts(source As String, target As String)
Dim chtObj As ChartObject
'First delete all charts from target sheet
DeleteEmbeddedCharts (target)
'Some delay
Application.Wait Now + TimeSerial(0, 0, 1)
For Each chtObj In ThisWorkbook.Worksheets(source).ChartObjects
With ThisWorkbook.Worksheets(target)
.Activate
chtObj.Copy
'Paste in row T1+i
Range("T1").Offset(i).Select
.Activate
Application.Wait Now + TimeSerial(0, 0, 1)
.Paste
Application.Wait Now + TimeSerial(0, 0, 1)
i = i + 10
.Activate
End With
Next chtObj
'Set the data references to target sheet
SetChartRef (target)
End Sub