How do I get a subset of elements in an array in excel vba?

╄→гoц情女王★ 提交于 2020-01-03 06:41:12

问题


How do I get the 3rd through 6th elements in an array in excel vba? Something like the following.

    Dim x(9) as variant, y(3) as variant

    y(0:3) = x(2:5)

回答1:


In VBA, unlike in python for example, we cannot directly "subset" an array.

We can only loop for the indices of interest by specifying i and j to be between certain bounds e.g. i to be between rows 1 and 2, j to be between columns 2 and 3. Of course, we can also directly index into the array by position e.g. arr(1). i just a variable representing the row index, j the column index.

Or, we can use Index to "slice" out a particular row or column; which I guess you might call subsetting but from your syntax I think you are thinking in the manner of python for example.

Application.WorksheetFunction.Index(array,n, 0) will slice row n out of array

Application.WorksheetFunction.Index(array, 0, n) will slice column n out of array

Option Explicit

Public Sub ArrayStuff()
    Dim arr(0 To 5) As Long, i As Long
    For i = 0 To 5
        arr(i) = i
    Next

    'Loop only required indices
    For i = 2 To 3
        Debug.Print arr(i)
    Next

    'Slice via Application.WorksheetFunction.Index
    Dim arr2(0 To 2, 0 To 2) As Long, j As Long, counter As Long

    For i = LBound(arr2, 1) To UBound(arr2, 1) '<==  here can specify particular rows
        For j = LBound(arr2, 2) To UBound(arr2, 2) '<== here can specify particular columns
            counter = counter + 1
            arr2(i, j) = counter
        Next
    Next

    MsgBox Join(Application.WorksheetFunction.Transpose(Application.WorksheetFunction.Index(arr2, 0, 1)), ",") 'slice a column out
    MsgBox Join(Application.WorksheetFunction.Index(arr2, 1, 0), ",") 'slice a row out
    MsgBox Join(Application.WorksheetFunction.Index(arr2, 2, 0), ",") 'slice a row out
End Sub



回答2:


For anyone who does not want to use loop or range method to deal this issue, here is a tested solution to process a subset (need not to be whole row or column) of an array:

Application.Sum(Application.Index(Array(1, 2, 3, 4, 5), 0, Evaluate("ROW(2:5)")))

which sums the 2nd to 5th element of the array (1, 2, 3, 4, 5). For an array with two dimensions, simply do the following:

Application.Average(.Index(DataArray, Evaluate("ROW(17:21)"), 5))

will calculate the average of the five elements subset (row 17 to 21, column 5) of the 2 dimensions array "DataArray".

BTW, I've not yet tried to evaluate the efficiency of this method, but it's truly a workaround. Hope this helps.



来源:https://stackoverflow.com/questions/50863989/how-do-i-get-a-subset-of-elements-in-an-array-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!