函数 returns i 给定项目的所有第 j 个元素

function that returns all the j-th elements of i given items

我想编写一个函数,其中 return 是 i 给定项的所有第 j 个元素。这些项目包含单个单元格、单元格区域或两者。

虽然可以 return 所有元素 (test1),每个第一个元素 (test2),但我无法 return 每个第二个(或以上)元素。

给定 Excel-Table

    B   C   D
2   X   1   333
3   X   2   666
4   Z   3   999

=test1((B2;C2;D2);B3:D3;(B4:C4;D4)) returns X 1 333 Y 2 666 Z 3 999

=test2((B2;C2;D2);B3:D3;(B4:C4;D4)) returns X Y Z

但是=test3((B2;C2;D2);B3:D3;(B4:C4;D4))returnsY 2 3,这是错误的。应该 return 1 2 3.

VBA-函数的代码如下:

Function Test1(ParamArray argArray() As Variant)
' return all elements of all items = OK
    For Each outer_arg In argArray
        For Each inner_arg In outer_arg
            Test1 = Test1 & " " & inner_arg
        Next inner_arg
    Next outer_arg
End Function

Function Test2(ParamArray argArray() As Variant)
' return only the 1st elemtent of each item = OK
    For Each outer_arg In argArray
        Test2 = Test2 & " " & outer_arg(1)
    Next outer_arg
End Function

Function Test3(ParamArray argArray() As Variant)
' return only the 2nd elemtent of each item = FAILS
    For Each outer_arg In argArray
        Test3 = Test3 & " " & outer_arg(2)
    Next outer_arg
End Function 

如何正确处理特定元素?

您无法可靠地直接索引到 multi-area 范围(第一个区域除外)。例如:

? Range("B4:C4,D4")(3).address '>> B5, not D4 

? Range("B4,C4,D4")(2).address '>> B5, not C4

你可以使用这样的东西:

Function GetNthCell(rng As Range, n As Long) As Range
    Dim i As Long, c As Range, a As Range, tCurr As Long, tPrev As Long
    For Each a In rng.Areas
        tCurr = a.Cells.Count
        If tPrev + tCurr >= n Then
            Set GetNthCell = a.Cells(n - tPrev)
            Exit Function
        End If
        tPrev = tPrev + tCurr
    Next a
End Function

Sub Test()
    Debug.Print GetNthCell(Range("a1:A5,B1:B5,C1"), 6).Address '>> B1
End Sub

试试这个 learn this

Function Test2(ParamArray argArray() As Variant)
' return all elements of all items = OK
    For Each outer_arg In argArray
        For Each inner_arg In outer_arg(1, 1)
            Test2 = Test2 & " " & inner_arg
        Next inner_arg
    Next outer_arg
End Function

Function Test3(ParamArray argArray() As Variant)
' return all elements of all items = OK
    For Each outer_arg In argArray
        For Each inner_arg In outer_arg(1, 2)
            Test3 = Test3 & " " & inner_arg
        Next inner_arg
    Next outer_arg
End Function

感谢@TimWilliams 向我展示了我误解了什么以及角标(单独的范围)是什么。我写了一个解决方案,它用一个简单的计数器遍历所有元素。适合我。

Function Test4(nmbr, ParamArray argArray() As Variant)
' return only the j-th argument (nmbr) of each element = OK

    For Each outer_arg In argArray
        cnt = 1
        For Each inner_arg In outer_arg
            If cnt = nmbr Then
                Test4 = Test4 & " " & inner_arg.Value
            End If
            cnt = cnt + 1
        Next inner_arg
    Next outer_arg
End Function