简体   繁体   English

VBA _错误9下标超出范围

[英]VBA _Error 9 Subscript out of range

Why do I get "Subscript out of range" on my line T(k) = Cells(k + 1, 4).Value - z ? 为什么在行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

At the point where you say T(k) = ... , your array T hasn't been allocated yet. 在您说T(k) = ... ,您的数组T尚未分配。 There isn't any such thing as T(0) yet. 还没有T(0)这样的东西。 Hence the "Subscript out of range" error. 因此出现“下标超出范围”错误。

Before indexing into T , you have to give T a size using ReDim . 在索引到T之前,必须使用ReDim赋予T大小。 For example: 例如:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM