假设标题行的第二列中的值显示到下一个标题行的行数(示例数据有一段时间后...),这将设置数据,插入图表和颜色点。
Sub DoCharts()
Dim iRow As Long, nRows As Long, iPt As Long, nPts As Long
Dim rXVals As Range, rYVals As Range, rColor As Range
Dim cht As Chart
With ActiveSheet.UsedRange
For iRow = 1 To .Rows.Count
If .Cells(iRow, 3).Value = 0 And Len(.Cells(iRow, 3).Text) > 0 Then
' value is zero and cell is not blank
'define X and Y values
nPts = .Cells(iRow, 2).Value
Set rXVals = .Cells(iRow + 1, 1).Resize(nPts)
Set rYVals = rXVals.Offset(, 1)
Set rColor = rXVals.Offset(, 2)
' chart
Set cht = ActiveSheet.Shapes.AddChart(xlXYScatter, , .Cells(iRow, 1).Top).Chart
' clear existing series
Do While cht.SeriesCollection.Count > 0
cht.SeriesCollection(1).Delete
Loop
' add desired series
With cht.SeriesCollection.NewSeries
.Values = rYVals
.XValues = rXVals
End With
' point color
For iPt = 1 To nPts
With cht.SeriesCollection(1).Points(iPt)
Select Case rColor.Cells(iPt)
Case 1 ' green
.MarkerForegroundColor = vbGreen ' use nicer colors, of course
.MarkerBackgroundColor = vbGreen
Case 2 ' blue
.MarkerForegroundColor = vbBlue
.MarkerBackgroundColor = vbBlue
Case 3 ' red
.MarkerForegroundColor = vbRed
.MarkerBackgroundColor = vbRed
End Select
End With
Next
End If
cht.HasLegend = False
iRow = iRow + nPts
Next
End With
End Sub
编辑 - 在同一个图表中绘制所有内容。
我做了一些小改动。我仍然使用每个数据块中的单个 X 值。但我假设整个系列都具有相同的颜色格式,所以我按系列而不是按点进行格式化。我将每个系列格式化为带有标记的线条,而不仅仅是标记。我还使用每个标题行中的第一个单元格作为系列名称,所以这些是图例中系列的区别。最后我没有重新定位图表,而是让 Excel 将其放置在默认位置。
Sub DoOneChart()
Dim iRow As Long, nRows As Long, iPt As Long, nPts As Long
Dim rXVals As Range, rYVals As Range, rName As Range
Dim iColor As Long
Dim cht As Chart
With ActiveSheet.UsedRange
For iRow = 1 To .Rows.Count
If .Cells(iRow, 3).Value = 0 And Len(.Cells(iRow, 3).Text) > 0 Then
' value is zero and cell is not blank
'define X and Y values
nPts = .Cells(iRow, 2).Value
Set rXVals = .Cells(iRow + 1, 1).Resize(nPts)
Set rYVals = rXVals.Offset(, 1)
iColor = .Cells(iRow + 1, 3).Value
Set rName = .Cells(iRow, 1)
' chart
If cht Is Nothing Then
Set cht = ActiveSheet.Shapes.AddChart(xlXYScatterLines).Chart
' clear existing series
Do While cht.SeriesCollection.Count > 0
cht.SeriesCollection(1).Delete
Loop
End If
' add desired series
With cht.SeriesCollection.NewSeries
.Values = rYVals
.XValues = rXVals
.Name = "=" & rName.Address(, , , True)
' series color
Select Case iColor
Case 1 ' green
.MarkerForegroundColor = vbGreen ' use nicer colors, of course
.MarkerBackgroundColor = vbGreen
.Border.Color = vbGreen
Case 2 ' blue
.MarkerForegroundColor = vbBlue
.MarkerBackgroundColor = vbBlue
.Border.Color = vbBlue
Case 3 ' red
.MarkerForegroundColor = vbRed
.MarkerBackgroundColor = vbRed
.Border.Color = vbRed
End Select
End With
End If
iRow = iRow + nPts
Next
cht.HasLegend = True
End With
End Sub