Summary

The LAMBDA function can be used to create custom, reusable functions. In the example shown, cell D5 contains the custom LAMBDA function "StripTrailingChars":

=StripTrailingChars(B5,C5)

The StripTrailingChars function is designed to accept two input parameters:  str is the text from which to remove trailing characters, and char is the trailing character to remove. In the example shown, StripTrailingChars is configured to remove the characters seen in column C from the text seen in column B. These characters will only be removed when they are "trailing", i.e. when they appear at the end of the string. This custom LAMBDA formula illustrates a feature called recursion, in which a function calls itself.

Note: the LAMBDA function is available through the beta channel of Excel 365 only.

Generic formula

=LAMBDA(str,char,
  IF(RIGHT(str)<>char,str,
    StripTrailingChars(
      MID(str,1,LEN(str)-1),
      char
    )
  )
)

Explanation 

LAMBDA function can be used to create custom, reusable functions in Excel. This example illustrates a feature called recursion, in which a function calls itself. Recursion can be used to create elegant, compact, non-redundant code. This example is primarily proof of concept, to show a very simple recursive LAMBDA function.

When creating a recursive LAMBDA formula a key consideration is how the formula will "exit" the loop it performs by calling itself. In this example, before the recursive call happens, the IF function is used to check the last character of the input text string (str). If the last character is not equal to the target character (char) the function exits and returns the current value of str. Otherwise, the formula calls itself:

=LAMBDA(str,char,
  IF(RIGHT(str)<>char,str, // test and exit if needed
    StripTrailingChars( // recurse
      MID(str,1,LEN(str)-1),
      char
    )
  )
)

The actual removal of the trailing character is handled by the MID function and LEN function:

MID(str,1,LEN(str)-1)

The MID function returns the value of str without the last character. MID strips one character at a time, which is why this formula is recursive. The result is given to the StripTrailingChars function, along with the original value for char. When all the target trailing characters have been removed, the function returns the current value for str.

You can find more general information about the LAMBDA function here.

Dave Bruns Profile Picture

AuthorMicrosoft Most Valuable Professional Award

Dave Bruns

Hi - I'm Dave Bruns, and I run Exceljet with my wife, Lisa. Our goal is to help you work faster in Excel. We create short videos, and clear examples of formulas, functions, pivot tables, conditional formatting, and charts.