gpt4 book ai didi

vba - 将新系列添加到图表 (VBA) 时出现应用程序定义或对象定义错误

转载 作者:行者123 更新时间:2023-12-04 21:53:35 25 4
gpt4 key购买 nike

我正在尝试从该页面上的单个数据表动态地将新图表系列添加到单个图表中。但是,在 .XValues 命令期间,我不断收到

Runtime error '1004': Application-defined or object-defined error.



我正在使用以下代码:
Sub addseries()

Dim endpt1 As Range
Dim endpt2 As Range
Dim Address1 As Range
Dim Address2 As Range

For x = 2 To (Sheets.Count - 1)
Cells(1, 2 * x - 1).Select
Selection.End(xlDown).Select
Set endpt1 = ActiveCell
Cells(1, 2 * x).Select
Selection.End(xlDown).Select
Set endpt2 = ActiveCell
Range(Cells(2, 2 * x - 1), endpt1).Select
Set Address1 = Selection
Range(Cells(2, 2 * x), endpt2).Select
Set Address2 = Selection

Debug.Print ("Last Row1: " & endpt1.Address & " Last Row2: " & endpt2.Address)
Debug.Print "x Range: " & Address1.Address
Debug.Print "Value Range: " & Address2.Address
'Add new series
ActiveSheet.ChartObjects("Chart 1").Activate
ActiveChart.SeriesCollection.NewSeries
'Set ranges for new series
ActiveChart.FullSeriesCollection(x).Name = ActiveSheet.Cells(1, 2 * x)
ActiveChart.FullSeriesCollection(x).XValues = "='Merged Plot'!Address1.Address()"
ActiveChart.FullSeriesCollection(x).Values = "='Merged Plot'!Address2.Address()"


Next x
End sub

这些是立即窗口中显示的值:
Last Row1: $C$62 Last Row2: $D$62
x Range: $C$2:$C$62
Value Range: $D$2:$D$62

最佳答案

我想是这样的。我会做很多其他的改变,但目前你应该注意的两件事是:

1) X 从 2 开始,但新系列从 1 开始,因此从 X 中删除 1,例如ActiveChart.SeriesCollection(x - 1).Values
2)C̶o̶n̶c̶a̶t̶e̶n̶a̶t̶e̶̶t̶h̶e̶̶a̶d̶d̶r̶e̶s̶s̶̶f̶o̶r̶̶s̶o̶u̶r̶c̶e̶̶d̶a̶t̶a̶̶̶e̶.̶g̶.̶̶̶ ̶"̶=̶'̶M̶e̶r̶g̶e̶d̶ ̶P̶l̶o̶t̶'̶!̶"̶ ̶&̶ ̶A̶d̶d̶r̶e̶s̶s̶2̶.̶A̶d̶d̶r̶e̶s̶s̶ ̶ ̶ 设置地址部分如下"=" & Address1.Address(False, False, xlA1, xlExternal) .

感谢@Shai Rado 关于使用 Address1.Address(False, False, xlA1, xlExternal) 的说明

Option Explicit

Sub addseries()

Dim endpt1 As Range
Dim endpt2 As Range
Dim Address1 As Range
Dim Address2 As Range

Dim x As Long

For x = 2 To (Sheets.Count - 1)

With ActiveSheet

.Cells(1, 2 * x - 1).Select
Selection.End(xlDown).Select
Set endpt1 = ActiveCell
.Cells(1, 2 * x).Select
Selection.End(xlDown).Select
Set endpt2 = ActiveCell
.Range(.Cells(2, 2 * x - 1), endpt1).Select
Set Address1 = Selection
.Range(.Cells(2, 2 * x), endpt2).Select
Set Address2 = Selection

Debug.Print ("Last Row1: " & endpt1.Address & " Last Row2: " & endpt2.Address)
Debug.Print "x Range: " & Address1.Address
Debug.Print "Value Range: " & Address2.Address

With ActiveSheet.ChartObjects("Chart 1").Chart
.SeriesCollection.NewSeries
.SeriesCollection(x - 1).Name = .Cells(1, 2 * x).Value
.SeriesCollection(x - 1).XValues = "=" & Address1.Address(False, False, xlA1, xlExternal)
.SeriesCollection(x - 1).Values = "=" & Address2.Address(False, False, xlA1, xlExternal)
End With

End With

Next x
End Sub

关于vba - 将新系列添加到图表 (VBA) 时出现应用程序定义或对象定义错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49509205/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com