簡體   English   中英

在VBA Excel中重用2D數組?

[英]Reusing 2D array in VBA Excel?

這里是新功能,也是VBA和一般編程的新功能。

我試圖(通過循環)重用多個數組,但是我想我需要在重用它們之前清除它們? 我曾嘗試搜索所有問題,但找不到解決方案,或者坦白地說,如果解決方案無法解決,我將無法理解。

Dim WS As Worksheet

For Each WS In Worksheets
    If Right(WS.Name, 4) = "Data" Then Comp = Comp + 1
Next WS

Dim CompArray(10, 50) As Variant
Dim RatesArray(10, 1 To 50) As Variant
Dim IndexArray(10, 50) As Variant
Dim ShortIndexArray(10) As Long
Dim MRow, DRow, FRow, RRow, Col As Long
Dim LastCol, LastRow As Long

MRow = 4
LastRow = Cells(Rows.Count, 1).End(xlUp).Row


Do Until MRow > LastRow

    '**** MY CODE ****

''''***!!!*** Trying to Clear the array and reuse with the same dimensions for each loop ***!!!***
' not working

''Erase CompArray, RatesArray, IndexArray, ShortIndexArray
''ReDim CompArray(10, 50)
''ReDim RatesArray(10, 1 To 50)
''ReDim IndexArray(10, 50)
''ReDim ShortIndexArray(10)

MRow = MRow + 6 + Comp
Loop




End Sub

因此,當我轉到主循環的下一步時,我要使用的數組具有相同的信息。 我想保持數組的名稱和維數相同,但要清除內容。 對我來說聽起來很簡單,但我不知道該怎么做。

我嘗試擦除和重新命名(這是此處類似問題的解決方案),但沒有奏效,實際上是在說我兩次聲明了陣列。

我也曾嘗試在循環中使數組變暗。 那也不起作用。

任何幫助,將不勝感激!

謝謝。

如果要重用數組,則在初次聲明時不應該指定尺寸

Dim CompArray() As Variant

然后,當您要初始化它時,請使用關鍵字Redim

ReDim CompArray(10, 50)

如果再次重新定義數組,則除非使用Preserve關鍵字,否則將丟失已經存儲在其中的所有數據

ReDim Preserve CompArray(10, 60)

如果您要重新定義數組並保留內容,則只能更改最后一個維度

因此ReDim Preserve CompArray(10, 80)將在您更改最后一個元素時起作用。 當您嘗試更改第一個元素並保留數據時ReDim Preserve CompArray(100, 80)將導致錯誤。

ReDim CompArray(100, 800)可以正常工作,但是您將丟失所有當前存儲的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM