如果你只想获取数组的子集,并且你已经知道你想要的元素的位置,那么你可以使用带有一个数组作为索引参数的
INDEX
函数。如下所示:
=INDEX({11,22,33,44,55},{2,3,5})
返回的是{22,33,55}
。但通常这并不太有用,因为你不知道它们的位置,而且我也不知道如何在没有用户定义函数(UDF)的情况下获取它们。
对于这种工作表内数组过滤,我所做的是编写一个具有以下形式的UDF:
'Filters an input sequence based on a second "comb" sequence.
'Non-False-equivalent, non-error values in the comb represent the positions of elements
'to be kept.
Public Function combSeq(seqToComb, seqOfCombValues)
'various library calls to work with 1xn or nx1 arrays or ranges as well as 1-D arrays
'iterate the "comb" and collect positions of keeper elements
'create a new array of the right length and copy in the keeper elements
End Function
我只发布了伪代码,因为我的实际代码都是调用库函数,包括收集位置和从位置复制的操作。这样做可能会掩盖基本思想,而该思想非常简单。
您可以像这样调用这样的UDF:
=combSeq({23, "", 34, 46, "", "16"}, {23, "", 34, 46, "", "16"} <> "")
或者
=combSeq(Q1:Q42, SIN(Z1:Z42) > 0.5)
可以使用Excel的标准数组来生成"comb"。这是一种轻量级的、适用于Excel的方式,能够获得大部分其他编程系统中更标准的filter(list-to-filter, test-function)
函数的优点。
我用"comb"这个名称,因为"filter"通常意味着"使用此函数进行过滤",而在Excel中,在调用过滤函数之前必须应用测试函数。此外,计算一个"comb"作为中间结果,然后将其用于......嗯,梳理...多个列表也可能很有用。