1

我想编写一个函数,返回 i 给定项目的所有第 j 个元素。这些项目包含单个单元格、单元格范围或两者。

虽然可以返回所有元素(test1),每个第一个元素(test2),但我无法返回每秒(或更高)的元素。

给定一个 Excel 表

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

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

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

但是=test3((B2;C2;D2);B3:D3;(B4:C4;D4))返回Y 2 3,这是错误的。它应该返回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 

如何正确处理特定元素?

4

3 回答 3

2

您不能可靠地直接索引到多区域范围(第一个区域除外)。例如:

? 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
于 2019-06-13T16:13:07.117 回答
0

试试这个并学习这个

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
于 2019-06-13T16:48:25.633 回答
0

感谢@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
于 2019-06-13T19:41:11.640 回答