Get our FREE VBA eBook of the 30 most useful Excel VBA macros.

Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.

Claim your free eBook


Office Scripts – Reverse number signs

Office Scripts - Worksheets

We often need to reverse number signs in Excel.  For me, this regularly occurs because the accounting signage for debits and credits is opposite to the signage of income and costs.  I am sure in your chosen field there are plenty of scenarios also.  Using native Excel functionality, there are plenty of ways to change numbers from positive to negative or vice versa.

Those native Excel methods are all well and good, but it can become a bit tiresome if we have to do it a lot.  If we’re using Excel online, having an Office Script perform the task for us can be much faster.  So, in this post, we’ll cover the code necessary to achieve this.

Technique

When using Office Scripts, the most common reason for slow running scripts is the amount of interaction with the workbook.  Therefore, it is optimal to read and write the data from and to the workbook as little as possible.  Anything which loops over a range cell by cell is likely to be very slow.  Instead, we can use arrays.  The high-level process is:

  1. Read the data into an array
  2. Manipulate the array
  3. Push the result back to the workbook

When using arrays, we have two good options for manipulating each item:

  1. for loop
  2. map method (which is specific for arrays).

For the purposes of flipping number signs, both achieve similar results and could be used interchangeably.  Therefore, in this post, I have included both methods so you can choose whichever you prefer.

Reverse number signs when all cells are values

If all the cells in a range contain values, the signage flipping can be applied to every item in the array.

The code examples in this section work with cell values; positive numbers are converted to negative, and negative are converted to positive.  As the script runs on values, it also converts any formulas to hardcoded values.

for loop approach

function main(workbook: ExcelScript.Workbook)
{

  //Declare and assign variable for the selected cells
  let rng = workbook.getSelectedRange();

  //Create array for the values in the range
  let arr = rng.getValues();

  //Loop through each item in the 2D array
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[0].length; j++) {

      //Flip signage value
      arr[i][j] = -arr[i][j]
    
    }
  }

  //Push array back to cells using the setValues method
  rng.setValues(arr);

};

Array map approach

function main(workbook: ExcelScript.Workbook)
{

  //Declare and assign variable for the selected cells
  let rng = workbook.getSelectedRange();

  //Create array for the values in the range
  let arr = rng.getValues();

  //Map through each item in the 2D array
  let newArr = arr.map(row => {
    return row.map (cell => {

      //Flip signage value
      return -cell;

    })
  });

  //Push array back to cells using the setValues method
  rng.setValues(newArr);

};

Reverse number signs when cells are mixed types

In the code below, we tackle the issue of formulas or text within the selected data range.  The key differences are:

  • Rather than the getValues and setValues methods, it uses the getFormulas and setFormulas.
  • An additional check has been added to test if the array element contains a number.
    • We use isNaN to assess if a value is not a number.  true = not a number, false = it is a number.
    • ! before isNaN reverses the true/false result.
  • The action to reverse number signs is only applied to those items that are numbers.

If the range contains any numbers preceded by an equals ( = ) symbol, these are treated as formulas.  For example:

  • 12 is a cell value
  • =12 is a formula in which the result is 12

for loop approach

function main(workbook: ExcelScript.Workbook)
{

  //Declare and assign variable for the selected cells
  let rng = workbook.getSelectedRange();

  //Create array for the values in the range
  let arr = rng.getFormulas();

  //Loop through each item in the 2D array
  for (let i = 0; i < arr.length; i++) {
    for (let j = 0; j < arr[0].length; j++) {

      //Check if the array item is a number     
      if (!isNaN(arr[i][j])) {

        //Flip signage value
        arr[i][j] = -arr[i][j]

      }
    }
  }

  //Push array back to cells using the setFormulas method
  rng.setFormulas(arr);

};

Array map method

function main(workbook: ExcelScript.Workbook)
{

  //Declare and assign variable for the selected cells
  let rng = workbook.getSelectedRange();

  //Create array for the values in the range
  let arr = rng.getFormulas();

  //Map through each item in the 2D array
  let newArr = arr.map(row => {
    return row.map (cell => {

      //Check item is a number, if true reverse
      if (!isNaN(cell)) {
        return -cell;
      } else {
        return cell;
      }
    })
  });

  //Push array back to cells using the setFormulas method
  rng.setFormulas(newArr);

};

Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn't until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I'm guessing the examples in this post don't exactly match your situation. We all use Excel differently, so it's impossible to write a post that will meet everybody's needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you're still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the 'Excel Ninja' in your office. It's amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it's clear and concise.  List all the things you've tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don't go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Leave a Reply

Your email address will not be published. Required fields are marked *