我想编写一个函数,该函数返回给定项的所有第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
如何正确处理特定元素?
答案 0 :(得分: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
答案 1 :(得分:0)
尝试此操作,然后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
答案 2 :(得分: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