在循环中使用if语句会创build一个无效的参数错误

我在Excel中编写了下面的代码来创build一个XY散点图并格式化这些点,以创build一个在特定时间段内(在sDateeDate之间)所做的事件/决策的可视时间线。

 Option Explicit Sub UpdateTimeline() 'Updates timeline chart with dates in specified range and updates formatting Dim timelineChart As Chart Dim recordCount As Long Dim record As Range Application.ScreenUpdating = False timelineSheet.Unprotect Call ClearSeries Set timelineChart = Worksheets("Timeline").ChartObjects("chtDecisionTimeline").Chart recordCount = 0 For Each record In Range(decisionRecordSheet.Range("D7"), decisionRecordSheet.Range("D7").End(xlDown)) recordCount = recordCount + 1 If record.Value >= timelineSheet.Range("sDate") Then If record.Value <= timelineSheet.Range("eDate") Then timelineChart.SeriesCollection.NewSeries With timelineChart.SeriesCollection(recordCount) .Name = "='Decision Record'!" & record.Offset(0, 1).Address .XValues = "='Decision Record'!" & record.Address .Values = "='Decision Record'!" & record.Offset(0, -2).Address .AxisGroup = 2 .MarkerStyle = 8 .MarkerSize = 7 .MarkerBackgroundColor = RGB(228, 10, 56) .MarkerForegroundColor = -2 .Format.Line.Visible = False .ApplyDataLabels .DataLabels.ShowValue = False .DataLabels.ShowSeriesName = True .DataLabels.Orientation = xlUpward If record.Offset(0, -2).Value Mod 2 <> 0 Then timelineChart.SeriesCollection(recordCount).DataLabels.Position = xlLabelPositionRight Else timelineChart.SeriesCollection(recordCount).DataLabels.Position = xlLabelPositionLeft End If End With End If End If Next timelineChart.SetElement (msoElementSecondaryValueAxisNone) With timelineChart.Axes(xlCategory, xlPrimary) .MaximumScale = timelineSheet.Range("eDate").Value .MinimumScale = timelineSheet.Range("sDate").Value End With With timelineChart.Axes(xlValue, xlPrimary) .MaximumScale = lookupSheet.Range("yMax").Value .MinimumScale = lookupSheet.Range("yMin").Value End With With timelineSheet .Protect DrawingObjects:=True, Contents:=True, Scenarios:=True .EnableSelection = xlUnlockedCells End With Application.ScreenUpdating = True End Sub 

decisionRecordSheet在BF列中包含以下格式的数据:

显示decisionRecordSheet数据布局的图像

timelineSheet列出如下:

在这里输入图像说明

代码工作正常(虽然我知道这不是很漂亮),除非用户指定的date范围(在sDateeDate )意味着只有0-2logging需要绘制在图上,在这种情况下,它抛出一个无效With timelineChart.SeriesCollection(recordCount)参数错误。

我已经尝试过注释18,19,42和43行,并且它看起来似乎是if语句减less了符合导致问题的条件的logging数。 我也尝试减less总数据集,所以只有0-2,我得到相同的错误。

当然,这可能与正在绘制的logging数量无关,但是这些是唯一一贯复制此行为的testing。

编辑:

当有两个以上的项目需要绘制时,我也会得到一个运行时错误,但是只有在我的代码中包含了第18,19,42和43行 – 如果我注释掉了,我不会再出错。

错误信息

当我debugging它似乎是timelineChart.SetElement (msoElementSecondaryValueAxisNone)的问题,但我不知道为什么。

我不能复制它,因为你打电话给代码,我们没有在这里,但:

如果您将recordCount = recordCount + 1移动到或更改

要么

timelineChart.SeriesCollection(recordCount)更改为timelineChart.SeriesCollection(timelineChart.SeriesCollection.Count)

这可能会提供一个积极的结果。 您用于查找集合的recordCount每次都会增加,但是有一个if语句表示可能不会每次都创build一个系列。