VBA / Excel:“下标超出范围”错误

我正在试图填充Hrs数组的条件是特定的单元格是否为空的条件:

 Sub Add_training_hrs() Dim Rng1, Rng2 As Range Dim m, n As Integer Dim Hrs() As Double Set Rng11 = Application.InputBox("Upper-left cell (eg, C4): ", "Box #1", Type:=8) Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8) Col11 = Rng11.Column Row11 = Rng11.Row Col22 = Rng22.Column Row22 = Rng22.Row nRows = Row22 - Row11 nCols = Col22 - Col11 ReDim Hrs(1 To nCols) Debug.Print "Hrs(1) = "; Hrs(1) For n = 1 To nRows For m = 1 To nCols If IsEmpty(Cells(n, m).Value) Then Hrs(m) = 0 Debug.Print "Hrs(m) = "; Hrs(m) Else Hrs(m) = Cells(Row11 - 1, m).Value End If Cells(n, Col22 + 1).Value = Application.Sum(Hrs) Erase Hrs Next m Next n End Sub 

出于某种原因,我不断收到“订阅出…”错误后我的Hrs(m) = 0If... Then我的If... Then语句,但我不明白为什么。 任何意见,赞赏,如果有一个重复的问题,可以帮助,不要犹豫,让我知道(我看了…)。


更新(和工作)的代码

我原来的脚本有各种各样的问题,但我得到它的工作。 我在这里发布它,以帮助其他人:

 Sub Add_training_hrs() Dim Rng11 As Range Dim Rng22 As Range Dim m As Integer Dim n As Integer Dim Hrs() As Double Set Rng11 = Application.InputBox("Upper-left cell (eg, C4): ", "Box #1", Type:=8) Set Rng22 = Application.InputBox("Lower-right cell: ", "Box #2", Type:=8) Col11 = Rng11.Column Row11 = Rng11.Row Col22 = Rng22.Column Row22 = Rng22.Row nRows = (Row22 - Row11) + 1 nCols = (Col22 - Col11) + 1 ReDim Hrs(1 To nCols) For n = 0 To nRows - 1 For m = 0 To nCols - 1 If IsEmpty(Cells(Row11 + n, Col11 + m).Value) Then Hrs(m + 1) = 0 Else Hrs(m + 1) = Cells(Row11 - 1, Col11 + m).Value End If Next m Cells(Row11 + n, Col22 + 1).Value = Application.Sum(Hrs) Erase Hrs ReDim Hrs(1 To nCols) Next n End Sub 

我想你只是从第二行开始的错误。

当您擦除dynamic数组时,您将释放内存(请参见擦除 )

你将需要重新分配之后。