0

How do I create a conditional formula for Google Spreadsheets where:

  • If the value of cell A1 is an even number, I want cell B2 to display the value of A1 * 2

  • If the value of cell A1 is an odd number, I want cell B2 to display the value of A1 + 1

Here's a basic blueprint for what I want to do:

function isEven(input) {
    if(input % 2 == 0) {
        return true;
    }
    else {
        return false;
    }
}

function conditionalFormula(input) {
    if(isEven(input)) {
        //Make cell B1's value equal to A1 * 2
    }
    else {
        //Make cell B1's value equal to A1 + 1
    }
}
5
  • Do you want to run this function or call it from within the Spreadsheet? Commented Oct 18, 2016 at 7:59
  • @RobinGertenbach I want to call it from within the spreadsheet Commented Oct 18, 2016 at 8:06
  • In that case can't you use the formula approach? Otherwise calling the function from a cell you can (and must) let the function return the value, not set it from within the script Commented Oct 18, 2016 at 8:11
  • I want to use a script because it's a cleaner approach for me and I want to use that know-how to do other things Commented Oct 18, 2016 at 9:24
  • In that case you just need the function to return input+1 or return input*2 respectively. Commented Oct 18, 2016 at 9:40

2 Answers 2

3

Can you not just use a combination of the built in ISEVEN and IF statements to achieve this?

i.e in cell B1 write:

=IF(ISEVEN(A1),A1*2,A1+1)

You can then copy and paste it which should automagically increment the cell index.

Sign up to request clarification or add additional context in comments.

1 Comment

This is correct! No need to write any script when Google Spreadsheet has so many inbuilt formulas to achieve what you need.
0

If you want to run this down a column, use the ARRAYFORMULA function so you do not have to copy it to each cell:

=ARRAYFORMULA(IF(ISEVEN(A1:A),A1:A*2,A1:A+1))

will give you a 0 if there is no value

=ARRAYFORMULA(IF(ISNUMBER(A1:A), IF(ISEVEN(A1:A),A1:A*2,A1:A+1), ""))

Will only multiple the value if the cell in Column A is a number.

In the above examples, the formula goes in row 1 and applies to the entire row. Change the Range from A1:A to A2:A20 if placed in row 2 and working on rows 2 through 20. Both formulas using A1:A will put a value (a number or blank element) in every cell in the column which contains the arrayformula. The A2:A20 version will only put those values inside cells 2-20.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.