如何使用excel公式返回名单?

时间:2015-09-08 07:32:56

标签: excel excel-formula

数据是:

-|-A--|-B-|
1|BAT | 5 |
2|CAT | 2 |
3|RAT | 4 |

如果列B中的值,我想要给出动物名单的公式> 3.
例如,结果是BAT,RAT。

2 个答案:

答案 0 :(得分:0)

以下是使用您可以获得所需内容的方法之一。但是您需要使用VBA帮助来创建用户定义的功能。

在excel中实现用户定义的功能:

1. Press Alt-F11 to open visual basic editor
2. Click Module on the Insert menu
3. Copy and paste below metioned user defined function
4. Exit visual basic editor  

这是功能:

Function Lookup_concat(Search_in_col As Range, Return_val_col As Range)

    Dim i As Long
    Dim result As String

    For i = 1 To Search_in_col.Count
        If Search_in_col.Cells(i, 1) > 3 Then
            If result = "" Then
                result = Return_val_col.Cells(i, 1).Value
            Else
                result = result & ", " & Return_val_col.Cells(i, 1).Value
            End If
        End If
    Next
    Lookup_concat = Trim(result)

End Function

现在在单元格C1中,粘贴公式:

=Lookup_concat(B2:B4,A2:A4)  

这将返回 BAT, RAT

解释用户定义的功能:
Lookup_concat(Search_in_column,Concatenate_values_in_column) 在列中查找大于3的值,然后从指定的列返回相同行中的值,并将其连接到单个单元格中。

答案 1 :(得分:0)

按照@ Nelly27281巧妙建议的VB方法,我建议使用以下函数,使用标准,范围,输入和输出列的变量,使其更加灵活。

'Variables  Type     Description                                                          Sample
'sCriteria  String   The criteria to search for                                           “>3”
'rInput     Range    The whole range to work with                                         A1:B4
'bColSearch Byte     Column within the rInput range to search for using “sCriteria”       2
'bColOutput Byte     Column within the rInput range to obtain the output value            1
'blHasHdr   Boolean  (Optional) True if the “rinput” range has header, default is false   1

Public Function rSearch_sOutput(sCriteria As String, _
    rInput As Range, bColSearch As Byte, bColOutput As Byte, Optional blHasHdr As Boolean)
Dim sOutput As String
Dim L As Long, L0 As Long

    Rem Set Output String
    L0 = IIf(blHasHdr, 2, 1)
    With rInput
        For L = L0 To .Rows.Count
            If Application.Evaluate(.Columns(bColSearch).Cells(L).Value2 & sCriteria) Then
                If sOutput = Empty Then
                    sOutput = .Columns(bColOutput).Cells(L).Value2
                Else
                    sOutput = sOutput & ", " & .Columns(bColOutput).Cells(L).Value2
    End If: End If: Next: End With

    Rem Set Results
    rSearch_sOutput = sOutput

End Function

要使用它,请输入以下公式:

=rSearch_sOutput(">3",A1:B4,2,1,1)