【发布时间】:2016-03-22 20:14:41
【问题描述】:
我是 VBA 新手,在尝试使用数组计算数字列表中的最大值时遇到错误 9 问题“下标超出范围”。我有一个跨越多个团队(作为 x 轴值)和类别(作为系列)的堆叠条形图。对于每个团队,每个类别都有数字(事故工单状态),我想找出哪个团队的工单数量最多,并使用该信息来格式化我的条形图。突出显示有问题的代码行。我已经阅读了许多关于错误 9 和 VBA 数组的先前线程,但问题仍然存在。谁能给我提示一下我的代码出了什么问题?我将不胜感激。
Sub ChangeByTeamChartColor()
Workbooks.Application.ActiveWorkbook.Sheets("By Team - Incident State").Select
ActiveSheet.ChartObjects("By Team Chart").Select
Dim s As Series
Dim teamTotal() As Integer
Dim seriesCount As Integer, seriesIterator As Integer, pointIterater As Integer
**ReDim teamTotal(1 To ActiveChart.SeriesCollection(1).Points.Count)**
'Iterate through series and set colors
For seriesIterator = 1 To ActiveChart.SeriesCollection.Count
Set s = ActiveChart.SeriesCollection(seriesIterator)
If s.Name = "Active >24 h" Or s.Name = "Active" Then
s.Format.Fill.ForeColor.RGB = RGB(192, 80, 77) 'Red Accent 2 Light 80
ElseIf s.Name = "Active <24 h" Or s.Name = "New" Then
s.Format.Fill.ForeColor.RGB = RGB(247, 150, 70) 'Orange
ElseIf s.Name = "Pending Customer" Then
s.Format.Fill.ForeColor.RGB = RGB(79, 129, 189) 'Blue
ElseIf s.Name = "Pending Vendor" Then
s.Format.Fill.ForeColor.RGB = RGB(128, 100, 162) 'Purple
ElseIf s.Name = "Scheduled" Then
s.Format.Fill.ForeColor.RGB = RGB(155, 187, 89) 'Green
ElseIf s.Name = "Closed" Or s.Name = "Resolved" Then
s.Format.Fill.ForeColor.RGB = RGB(148, 138, 84) 'Brown
ElseIf s.Name = "Unassigned" Then
s.Format.Fill.ForeColor.RGB = RGB(255, 192, 0) 'Yellow
End If
'Find the "Grand Total" datapoint in each series and hide it
For pointIterater = 1 To s.Points.Count
If s.XValues(pointIterater) = "Grand Total" Then
s.Points(pointIterater).Interior.ColorIndex = xlNone
End If
' The following line gives the error ===================================
teamTotal(pointIterator) = teamTotal(pointIterator) + s.Values(pointIterator)
' ========================================================================
Next pointIterater
Next seriesIterator
结束子
【问题讨论】:
-
数组索引为零。第一个元素是“0”,通过 .Count 循环到集合末尾时必须小心。你想在 .Count - 1 结束它
-
"有问题的代码行被突出显示。"
-
@roryap 我假设它是从底部算起的第三行,带有两个星号,以及 For 循环之前数组的 ReDim。
-
两个字:
Option Explicit。您已声明pointIteratEr,但随后使用pointIteratOr作为索引。