EXCEL return 基于条件的值范围

EXCEL return range of values based on criteria

我有一个 VBA 函数,我想仅当 table 中的某些条件时才传递自定义范围的数据(与完整的 table 列范围相反)被满足。例如:

          Table_1                            Table_2
    A        B         C                A          B
1 Policy    Data     Status     |   1 Policy    Function
  --------------------------    |     -------------------
2   AA      25      approved    |   2   AA      [25, 35]
3   AA      19      unapproved  |   3   BB      [16]
4   BB      16      approved    |
5   CC      27      approved    |
6   CC      30      unapproved  |
7   AA      35      approved

在表 2 的单元格 B2 中,我想 return 表 1 中所有 Data 值的范围,其中 Policy = AAStatus = approved。随后,在单元格 B3 中的一系列值,其中 Policy = BBStatus = approved 等..

这可以用公式实现吗?

如果您有 Office 365 Excel 或更高版本,您可以使用 TEXTJOIN 作为数组公式:

="[" & TEXTJOIN(",",TRUE,IF(($A:$A=F2)*($C:$C="approved"),$B:$B,"")) & "]"

作为数组公式,退出编辑模式时需要使用 Ctrl-Shift-Enter 而非 Enter 进行确认。


如果您没有 Office 365 Excel 或更高版本,这里有一个 UDF 可以满足您的需求:

Function TEXTJOINIFS(rng As Range, delim As String, ParamArray arr() As Variant)
    Dim rngarr As Variant
    rngarr = Intersect(rng, rng.Parent.UsedRange).Value

    Dim condArr() As Boolean
    ReDim condArr(1 To Intersect(rng, rng.Parent.UsedRange).Rows.Count) As Boolean


    Dim i As Long
    For i = LBound(arr) To UBound(arr) Step 2
        Dim colArr() As Variant
        colArr = Intersect(arr(i), arr(i).Parent.UsedRange).Value
        Dim j As Long
        For j = LBound(colArr, 1) To UBound(colArr, 1)

            If Not condArr(j) Then
                Dim charind As Long
                charind = Application.Max(InStr(arr(i + 1), ">"), InStr(arr(i + 1), "<"), InStr(arr(i + 1), "="))
                Dim opprnd As String
                If charind = 0 Then
                    opprnd = "="
                Else
                    opprnd = Left(arr(i + 1), charind)
                End If
                Dim t As String
                t = """" & colArr(j, 1) & """" & opprnd & """" & Mid(arr(i + 1), charind + 1) & """"
                If Not Application.Evaluate(t) Then condArr(j) = True
            End If
        Next j
    Next i

    For i = LBound(rngarr, 1) To UBound(rngarr, 1)
        If Not condArr(i) Then
            TEXTJOINIFS = TEXTJOINIFS & rngarr(i, 1) & delim
        End If
    Next i

    TEXTJOINIFS = Left(TEXTJOINIFS, Len(TEXTJOINIFS) - Len(delim))

End Function

您可以将其称为 SUMIFS:

=TEXTJOINIFS(B:B,",",A:A,F2,C:C,"approved")

它只适用于列而不适用于行。