问题
I want to create a 1D array from a 2D array without looping using only 1 line of code such as:
newvec = oldvec(:,3)
which in MATLAB would create a 1D array "newvec" from the 3rd column of "oldvec". My searching tells me the only way to do this in VBA is looping. For example:
redim newvec(ubound(oldvec,1))
for i = 1 to ubound(oldvec,1)
newvec(i) = oldvec(i,3)
next i
Is there a built in construct for stripping our entire singular dimensions of an existing 2D array to build a new 1D array?
回答1:
There is no builtin function in VBA for this purpose unlike most common programming languages. However there is a workaround using Index function:
Application.Index(MultidimArray, Row_Number, Column_Number)
To extract a column from the source array, ‘0’ should be passed as row_number argument. Similarly, to extract a row from source array, ‘0’ should be passed as column_number argument.
So if you want to create a 1D array "newvec" from the 3rd column of "oldvec":
newvec = Application.Index(oldvec, 0, 3)
Here you can find more.
Edit:
Using For loop is a lot faster than using Index function. So you better stick with for loop. See comments for details.
回答2:
Tested writing to a range then back as well.
Tehscript's post is correct.
On my test the For loop was five times faster than Index, 10x faster then writing to a range then dumping the third column back to a 1D array.
Sub Test()
Dim X
Dim Y
Dim lngCNt As Long
Dim dbTimer As Double
X = [a1:c1000000].Value2
dbTimer = Timer()
'test 1
'Y = Application.Index(X, 0, 3)
'test 2
'ReDim Y(1 To UBound(X))
'For lngCNt = 1 To UBound(Y)
'Y(lngCNt) = X(lngCNt, 3)
'Next
'test 3
[d1:f1000000].Value2 = X
Y = Application.Transpose([f1:f1000000])
Debug.Print Timer() - dbTimer
End Sub
来源:https://stackoverflow.com/questions/43706522/stripping-column-or-row-to-make-1d-array