2016-05-23 24 views
0

我正在根據是否滿足工作表中的條件來滿足數組。問題是,我不知道數組有多長,因爲它可能比數據集本身大(將有一些條目重複)。我有什麼是沿着線的東西:有可能有一個沒有上限的數組?

Sub ArrayTest 
Dim MyArray as Variant 
Dim i as Long 
Dim index as Long 
Dim lastRow As Long 

lastRow = Cells(Rows.Count, 1).End(xlUp).row 
ReDim myarray(index) 

For i = 1 to lastrow 
    If (something) then 
     index = index + 1 
     ReDim Preserve recordArrray(Index) 
     recordArrray(Index) = range("A" & i) 

    End If 
Next 
End Sub 

然而,一旦index達到lastrow,我得到一個subscript out of range錯誤。我可以通過簡單地用ReDim myarray(1 to 100000000).替換ReDim行來避免這種情況。顯然,這不是一個理想的解決方案。

我可以創建一個數組而不必定義上限在創建之前是什麼?

+1

你總是必須定義上限。另一種選擇是每隔一段時間使用「Redim Preserve」,可能大小爲1000,或者使用集合(或字典)。 –

+1

如果你不想過於頻繁地重做數組,那麼你可能需要一個[dictionary](http://stackoverflow.com/questions/915317/does-vba-have-dictionary-structure)。在你的例子中,索引不應該高於lastrow,並且在循環之後使用上限和redimming可能更有效。編輯:在鏈接問題中也有一個集合示例 – arcadeprecinct

回答

0

數組始終必須同時具有上限和下限(儘管您可以使用Redim動態更改邊界)。

我的猜測是,你遇到的問題是索引的起始值是0這是超出你的數組的合法界限。我懷疑這會解決眼前的問題:

Sub ArrayTest 
Dim MyArray as Variant 
Dim i as Long 
dim index as Long 
Dim lastRow As Long 

lastRow = Cells(Rows.Count, 1).End(xlUp).row 
ReDim myarray(1 to lastrow) 

For i = 1 to lastrow 
    If (something) then 
     index = index + 1 
     recordArrray(Index) = range("A" & i) 
    End If 
Next 
End Sub 
+0

非常好。謝謝。循環中的調光工作。我已經更新了原來的問題。 – user1996971

相關問題