我录制了一个宏,它产生了以下代码,可以按照需要运行:
ActiveSheet.Shapes.AddChart2(227, xlLine).Select
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(1).Name = "=Graph!$B$1"
ActiveChart.FullSeriesCollection(1).Values = "=Graph!$B$3:$B$170"
ActiveChart.FullSeriesCollection(1).XValues = "=Graph!$A$3:$A$170"
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(2).Name = "=Graph!$H$1"
ActiveChart.FullSeriesCollection(2).Values = "=Graph!$H$3:$H$367"
ActiveChart.FullSeriesCollection(2).XValues = "=Graph!$G$3:$G$367"
我围绕该宏构建了我的代码:
Dim LastRow As Long, LastRow1 As Long, LastRow2 As Long
Dim P1Rating As Range
Dim P2Rating As Range
Dim DateRange As Range
Dim ShName As String
With ActiveSheet
' gets the lengths of each row
LastRow1 = .Range("B" & .Rows.Count).End(xlUp).Row
LastRow2 = .Range("G" & .Rows.Count).End(xlUp).Row
' checks to see which one is longer
If LastRow1 >= LastRow2 Then
LastRow = LastRow1
Else
LastRow = LastRow2
End If
' assigns the longer count to each range
Set P1Rating = .Range("B3:B" & LastRow)
Set date1range = .Range("A3:A" & LastRow)
Set P2Rating = .Range("H3:H" & LastRow)
Set date2range = .Range("G3:G" & LastRow)
ShName = .Name
End With
ActiveSheet.Shapes.AddChart2(227, xlLine, 600, 20).Select
indexofchart = ActiveChart.Parent.Index
ActiveSheet.ChartObjects(indexofchart).Activate
ActiveChart.HasTitle = True
ActiveChart.ChartTitle.Text = P1Name & " vs " & P2Name
ActiveChart.HasLegend = True
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(1).Name = P1Name
ActiveChart.FullSeriesCollection(1).Values = P1Rating
ActiveChart.FullSeriesCollection(1).XValues = date1range
ActiveChart.SeriesCollection.NewSeries
ActiveChart.FullSeriesCollection(2).Name = P2Name
ActiveChart.FullSeriesCollection(2).Values = P2Rating
ActiveChart.FullSeriesCollection(2).XValues = date2range
我正在使用:
If LastRow1 >= LastRow2 Then
LastRow = LastRow1
Else
LastRow = LastRow2
强制使用所有变量的最大范围,并验证使用了正确的值。 如您所见,我只是用变量替换宏中的硬范围 不幸的是,如果date1range是一个较小的范围,那么图形会在该点停止(两个系列在图表中显示为100%,但是超过该点的系列2中的任何数据都会丢失) 但是在录音中,该系列只有167长,图表显示了整个364个条目(更长的范围)。第一个系列结束了图表的1/3 如果该范围较大,则按预期显示。 如果没有强制图表首先使用更长的范围,我该怎么办?
答案 0 :(得分:0)
我发现了一个简单而优雅的解决方案应该可以很好地工作。我在这里找到了答案:https://peltiertech.com/plot-two-time-series-with-different-dates/
只需将所有日期值放入一列即可!
| 9/15/2015 | 1400 | a | | | | | | |
| 9/16/2015 | 1398 | a | | | | | | |
| 9/16/2015 | 1399 | d | | | | | | |
| 9/20/2015 | 1401 | b | | | | | | |
| 9/15/2015 | | | 1400 | a | | | | |
| 9/15/2015 | | | 1398 | c | | | | |
| 9/20/2015 | | | 1406 | c | | | | |
| 9/20/2015 | | | 1407 | d | | | | |
| 9/20/2015 | | | 1408 | b | | | | |