VBA – Redim an Array

转载自:http://www.dailydoseofexcel.com/archives/2004/06/28/redim-an-array/

Array variables can be static or dynamic. That’s determined by the Dim statement. If you specify dimensions when you declare the variable, it’s static and always will be. If you leave the dimensions blank in the Dim statement, it’s dynamic and can be changed.

Dim Array1(1To 10) As String ‘static arrayDim Array2() AsString ‘dynamic array

Dynamic arrays can be changed using the Redim statement.

Dim Arr1()As Double

ReDim Arr1(Selection.Columns.Count, Selection.Rows.Count)

If you use Redim, all the data in your array is lost, unless you use the Preserve keyword. This keeps the data in tact, but limits what you can change with a Redim. For instance, when you use Preserve, you can only change the last dimension of the array. Sometimes you have to organize your array horizontally to accomodate this restriction.

Dim Arr1()As DoubleDim cell As RangeDim i As Long

For Each cellIn Range(“A1:A100?).CellsIf cell.Value < 0.5 Theni = i + 1ReDim Preserve Arr1(1To 2, 1 To i)Arr1(1, i) = cell.ValueArr1(2, i) = cell.RowEnd IfNext cell

Preserve is an expensive keyword, so you use it sparingly. Many people will Redim their arrays in blocks to avoid having to do it in every iteration of a loop.

ReDimPreserve Arr1(1 To 2, 1To 10)

For Each cellIn Range(“A1:A100?).CellsIf cell.Value < 0.5 Theni = i + 1If i Mod 10 = 0 ThenReDim Preserve Arr1(1To 2, 1 To i + 10)End IfArr1(1, i) = cell.ValueArr1(2, i) = cell.RowEnd IfNext cell

I’m not a big fan of the block Redim, but if you have a really time intensive procedure and this shaves some valuable milliseconds, then go for it. If there’s a way to figure out the upper bounds of the array before you add data, then you may save time there also.

Dim SmallCellsAs Long

SmallCells = Application.Evaluate(“=sumproduct(–(a1:A100<.5))”)

ReDim Arr1(1 To 2, 1To SmallCells)

For Each cellIn Range(“A1:A100?).CellsIf cell.Value < 0.5 Theni = i + 1Arr1(1, i) = cell.ValueArr1(2, i) = cell.RowEnd IfNext cell

你曾经说,最大的愿望,

VBA – Redim an Array

相关文章:

你感兴趣的文章:

标签云: