excel vba基于点值更改数据点的条形图颜色


我有一些图表,其中X值是文本,Y值是数字。 如果条的Y值小于零,我想为每个条打上红色;如果大于或等于零,则为绿色。 另外,如果栏的X值是“NET CHANGE”,我需要栏是黄色的。 我遵循以前的StackOverflow线程中的指示: 使用基于类别标签的VBA更改栏颜色 。

我得到运行时错误451属性让程序没有定义和属性获取过程没有返回一个对象。

我的代码如下:

For chartIterator = 1 To ActiveSheet.ChartObjects.count For pointIterator = 1 To ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator).Chart.SeriesCollection(1).Points.count If ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator).Chart.SeriesCollection(1).Values(pointIterator) >= 0 Then ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator).Chart.SeriesCollection(1).Points(pointIterator).Interior.Color = _ RGB(146, 208, 80) Else ActiveWorkbook.Sheets("Due To Chart").ChartObjects(chartIterator).Chart.SeriesCollection(1).Points(pointIterator).Interior.Color = _ RGB(255, 0, 0) End If Next pointIterator Next chartIterator 

IF语句出现错误。 我也试过.Points(pointIterator).Value,它给了我一个“没有为这个对象定义的属性或方法”的错误。

任何想法,我在做什么错了?

在此先感谢您的帮助。

您在使用SeriesCollection(1).Values时遇到了麻烦,您将其视为可以迭代的数组。 相反,这是一个返回SeriesCollection中的点的值的函数。

所需要的是将函数的结果赋值给一个数组variables,然后迭代该数组以testing数组中的值是大于还是小于零。 然后,您可以将颜色分配给图表点。

这个代码应该做的伎俩:

  Sub color_chart() Dim chartIterator As Integer, pointIterator As Integer, _ seriesArray() As Variant For chartIterator = 1 To ActiveSheet.ChartObjects.Count seriesArray = ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator). _ chart.SeriesCollection(1).Values For pointIterator = 1 To UBound(seriesArray) If seriesArray(pointIterator) >= 0 Then ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator). _ chart.SeriesCollection(1).Points(pointIterator).Interior.Color = _ RGB(146, 208, 80) Else ActiveWorkbook.Sheets("Sheet1").ChartObjects(chartIterator). _ chart.SeriesCollection(1).Points(pointIterator).Interior.Color = _ RGB(255, 0, 0) End If Next pointIterator Next chartIterator End Sub 

这是一个不需要VBA的替代scheme,并且随着公式更新而dynamic工作。 查看本教程中的“条件格式化条形图”示例:

Excel图表中的条件格式