Is there a coalesce-like function in Excel?

故事扮演 提交于 2019-11-28 19:07:13
=INDEX(B2:D2,MATCH(FALSE,ISBLANK(B2:D2),FALSE))

This is an Array Formula. After entering the formula, press CTRL + Shift + Enter to have Excel evaluate it as an Array Formula. This returns the first nonblank value of the given range of cells. For your example, the formula is entered in the column with the header "a"

    A   B   C   D
1   x   x   y   z
2   y       y   
3   z           z
neil collins

I used:

=IF(ISBLANK(A1),B1,A1)

This tests the if the first field you want to use is blank then use the other. You can use a "nested if" when you have multiple fields.

Or if you want to compare individual cells, you can create a Coalesce function in VBA:

Public Function Coalesce(ParamArray Fields() As Variant) As Variant

    Dim v As Variant

    For Each v In Fields
        If "" & v <> "" Then
            Coalesce = v
            Exit Function
        End If
    Next
    Coalesce = ""

End Function

And then call it in Excel. In your example the formula in A1 would be:

=Coalesce(B1, C1, D1)

Taking the VBA approach a step further, I've re-written it to allow a combination of both (or either) individual cells and cell ranges:

Public Function Coalesce(ParamArray Cells() As Variant) As Variant

    Dim Cell As Variant
    Dim SubCell As Variant

    For Each Cell In Cells
        If VarType(Cell) > vbArray Then
            For Each SubCell In Cell
                If VarType(SubCell) <> vbEmpty Then
                    Coalesce = SubCell
                    Exit Function
                End If
            Next
        Else
            If VarType(Cell) <> vbEmpty Then
                Coalesce = Cell
                Exit Function
            End If
        End If
    Next
    Coalesce = ""

End Function

So now in Excel you could use any of the following formulas in A1:

=Coalesce(B1, C1, D1)
=Coalesce(B1, C1:D1)
=Coalesce(B1:C1, D1)
=Coalesce(B1:D1)

Inside the array enter the variables that are not allowed.

Function Coalesce(ParamArray Fields() As Variant) As Variant

    Dim v As Variant

    For Each v In Fields
        If IsError(Application.Match(v, Array("", " ", 0), False)) Then
            Coalesce = v
            Exit Function
        End If
    Next
    Coalesce = ""

End Function
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!