2017-10-13 128 views
0

爲什麼我的行T(k) = Cells(k + 1, 4).Value - z上會出現「下標超出範圍」?VBA _Error 9下標超出範圍

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 
+0

[填充VBA動態數組]的可能的複製(https://stackoverflow.com/questions/8850984/populating-vba-dynamic-arrays) –

+0

這個問題解決您的問題:https://開頭stackoverflow.com/questions/8850984/populating-vba-dynamic-arrays/8851086#8851086確保閱讀不僅僅是第一個答案! –

回答

0

,在您說T(k) = ...點,你的陣列T尚未分配。目前還沒有T(0)這樣的東西。因此「下標超出範圍」錯誤。

在索引到T之前,您必須使用ReDimT一個大小。例如:

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