There are a few ways of achieving this:
1. The LAMBDA function
Excel has had the LAMBDA()
function for quite a while, and now (as of August 2022) Google Sheets supports it too. LAMBDA()
can be used for this purpose.
It looks like this:
=LAMBDA(x, IF(x < 0, x + 1, x))(A1+B1)
Basically it creates a function on the fly and then you can pass whatever parameter (or multiple parameters) into the custom function.
In this way you only have to write your initial expression A1+B1
once (rather than 3 times), and can pass that into another function for doing the IF()
logic.
2. A Custom Apps Script Function
You could write the logic as a custom Apps Script function by clicking Extensions > Apps Script and adding your logic using Javascript:
function myLogic(x) {
return x < 0 ? x + 1 : x;
}
You can then call this in your spreadsheet whenever you need it via:
=myLogic(A1+B1)
The two downsides to this are:
Apps Script functions are run on Google servers with a slight delay and this can be a bit annoying when dealing with large amounts of data
The syntax for Javascript is different to that of Excel/GSheets which is an additional learning curve. Javascript can be very powerful, however, so learning some of the basics can be useful knowledge for those more advanced requirements.
3. Use Another Cell to Store the Intermediate Value
You can use another column which could be hidden from view (or even in another sheet) to store the intermediate variable:
=A1+B1
And then just have your logic:
=IF(C1 < 0, C1 + 1, C1)
The result will show faster than an Apps Script function and this will often be more maintainable in the long run than your original formula, especially when formulas get complex.
It doesn't feel quite as clean, though, I agree, and may require that you "fill down" the intermediate formulas when new rows are added (difficult when the column is hidden or stored in another sheet), unless you make use of array formulas which can auto-populate based on the source data.
Final Tip: Using Array Formulas
As an example of using an array formula, instead of having =A1+B1
and =A2+B2
in your intermediate cells, you have only a single formula in the top cell which is:
=ArrayFormula(A1:A100+B1:B100)
This will loop through the ranges and do A1+B1
, A2+B2
etc. and will populate all the necessary rows without needing to "fill down" when new data is added.
Hope this helps others.
(A1 + B1) + IF((A1 + B1) < 0, 1, 0)