VBA _Error 9下标超出范围

时间:2017-10-13 10:56:51

标签: vba excel-vba excel

为什么我得到"下标超出范围"在我的T(k) = Cells(k + 1, 4).Value - z号线上?

Public Sub find()
Dim i, j, k, h As Integer
Dim T() As Double
Dim z As Double
Range("E1").Activate
i = ActiveCell.Row
j = ActiveCell.Column
While Not IsEmpty(Cells(i, j - 2).Value)
  z = Cells(i, j - 2).Value
  k = 0
 While Not IsEmpty(Cells(k + 1, 4).Value)
  T(k) = Cells(k + 1, 4).Value - z
  k = k + 1
 Wend
  For h = 0 To k
   If T(h) = Application.WorksheetFunction.Min(Abs(T(k))) Then
    Cells(i, j).Value = Cells(h + 1, 4).Value
   End If
  Next
 i = i + 1
Wend
End Sub

1 个答案:

答案 0 :(得分:0)

在您说T(k) = ...时,您的数组T尚未分配。还没有T(0)之类的东西。因此“下标超出范围”错误。

在建立T索引之前,您必须使用TReDim提供一个大小。例如:

Dim T() As Double
ReDim T(0 to 123)  ' or whatever size you need