我正在尝试创建一个绘制 X 和 Y 点的图表,但在每个系列的每个 X 点之间绘制一条线。有点像这样:
但是我的问题是我如何定义我的 Xvalues
和 Values
在 SeriesCollection
的 VBA。这是因为我的值实际上存储在数组中。我使用了数组,因为我有以下数据:
ID Age1 Age2 Per
1 21 22 54.2%
2 19 23 68.6%
3 18 23 42.0%
4 30 33 45.1%
5 17 19 33.0%
6 19 22 41.3%
7 22 27 20.4%
8 19 20 56.4%
9 30 33 42.8%
10 21 22 59.7%
所以我需要在 X 轴上绘制
Age1
中的值和 Age2
.对应的Y值在Per
柱子。但我需要为每个 ID.
创建一个新系列我有以下代码并标记了问题所在。请注意,它不会编译。我认为问题在于我如何通过值来创建 XY 图表。我只想将值传递到图表上。Sub name()
Dim age1 As Variant
Dim age2 As Variant
Dim per1 As Variant
Dim per2 As Variant
Dim id As Variant
Dim ln As Integer
Dim cht As Chart
Dim wb As Workbook
Dim ws As Worksheet
Dim xdata As Varaint
Dim ydata As Varaint
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
id = ws.Range("A2", Range("A2").End(xlDown)).Value
age1 = ws.Range("B2", Range("B2").End(xlDown)).Value
age2 = ws.Range("C2", Range("C2").End(xlDown)).Value
per1 = ws.Range("D2", Range("D2").End(xlDown)).Value
per2 = ws.Range("D2", Range("D2").End(xlDown)).Value
ln = UBound(id) - LBound(id) + 1
Set cht = ws.ChartObjects("chart").Chart
With cht
.ChartArea.ClearContents
.ChartType = xlXYScatter
For i = 1 To ln
xdata=Array(age1(i),age2(i)) 'I assumed this would get the values in age1(i) and age2(i) and plot those as the xdata
ydata=Array(per1(i),per2(i)) 'Same error as above, but would use ydata
.SeriesCollection.NewSeries
.SeriesCollection(i).XValues = xdata
.SeriesCollection(i).Values = ydata
.SeriesCollection(i).Name = id(i)
Next i
End With
End Sub
最佳答案
问题是如何调用数组的各个部分。 age1
数组,连同其他数组,是二维的。所以而不是age1(i)
你想要age1(i,1)
这样i
是行和 1
是列。
Dim xdata As Variant
Dim ydata As Variant
Set wb = ThisWorkbook
Set ws = wb.Sheets(1)
id = Range(Range("A2"), Range("A2").End(xlDown)).Value2
age1 = Range(Range("B2"), Range("B2").End(xlDown)).Value2
age2 = Range(Range("C2"), Range("C2").End(xlDown)).Value2
per1 = Range(Range("D2"), Range("D2").End(xlDown)).Value2
per2 = Range(Range("D2"), Range("D2").End(xlDown)).Value2
ln = UBound(id) - LBound(id) + 1
Set cht = ws.ChartObjects("chart").Chart
With cht
.ChartArea.ClearContents
.ChartType = xlXYScatterLines
For i = 1 To ln
xdata = Array(age1(i, 1), age2(i, 1))
ydata = Array(per1(i, 1), per2(i, 1))
.SeriesCollection.NewSeries
.SeriesCollection(i).XValues = xdata
.SeriesCollection(i).Values = ydata
.SeriesCollection(i).Name = id(i, 1)
Next i
End With
关于excel - 在图表中使用数组值作为 X 和 Y 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52007061/