我有创建散点图的代码(时间对数据列)。还有第三列说明数据是“通过”还是“失败”(数据来自一组经过测试的样本)。
我想知道,是否存在可以对第三列进行排序的算法,并且基于它是否显示“已通过”或“失败”,它会将相应行中相应的时间和数据单元添加到一系列的?会有两个系列:一个用于传递,一个用于失败。 x值是时间,y值是数据。
我已编写的代码如下所示,用于创建包含该系列的图表以及它如何查找数据范围(动态更改):
Sub AddCharts()
Dim TSht As Worksheet
Dim Cht as Chart
With TSht
'Find last row in data
LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
'Create Chart
Set Cht = .Shapes.AddChart.Chart
With Cht
.ChartType = xlXYScatter
.SeriesCollection.NewSeries
With .SeriesCollection(1)
.XValues = TSht.Range(Cells(2, 6), Cells(LRow, 6))
.Values = TSht.Range(Cells(2, 7), Cells(LRow, 7))
End With
End With
End With
End Sub
答案 0 :(得分:1)
测试:
Sub AddCharts()
Dim TSht As Worksheet
Dim Cht As Chart, LRow As Long
Dim xP As Range, yP As Range, xF As Range, yF As Range
Dim rng As Range, c As Range
Set TSht = ActiveSheet
With TSht
'Find last row in data
LRow = .Cells(.Rows.Count, 1).End(xlUp).Row
'e.g. Pass/Fail is in Col 5
Set rng = .Range(.Cells(2, 5), .Cells(LRow, 5))
For Each c In rng.Cells
If c.Value = "Pass" Then
AddTo xP, c.Offset(0, 1)
AddTo yP, c.Offset(0, 2)
End If
If c.Value = "Fail" Then
AddTo xF, c.Offset(0, 1)
AddTo yF, c.Offset(0, 2)
End If
Next c
'Create Chart
Set Cht = .Shapes.AddChart.Chart
With Cht
.ChartType = xlXYScatter
With .SeriesCollection.NewSeries
.Name = "Pass"
.XValues = xP
.Values = yP
End With
With .SeriesCollection.NewSeries
.Name = "Fail"
.XValues = xF
.Values = yF
End With
End With
End With
End Sub
'utility sub for building up X and Y ranges
Sub AddTo(rng As Range, rngAdd As Range)
If rng Is Nothing Then
Set rng = rngAdd
Else
Set rng = Application.Union(rng, rngAdd)
End If
End Sub