Excel Tip: Using Index to calculate a cumulative sum (e.g. a Year to Date total)

From the Not Just Numbers blog:

Let me start with an apology. My current workload has meant that my posts have been a lot less frequent in recent weeks. This may continue for a while, but I will still be aiming to post at least once a month during this busy spell.

In this post I want to show you how to do something I have shown before using OFFSET, but this time using the more efficient INDEX.

Let’s look at the example of a 12 month budget spreadsheet with the monthly sales figures in cells B9 to M9 (month 1 in B9, Month 2 in C9, etc.). And let’s say that the current month number is entered in cell B6.

Using OFFSET we could return the current month’s sales using:

=OFFSET($B9,0,$B$6-1)

and the cumulative sales using:

=SUM(OFFSET($B9,0,0,1,$B$6))

See this earlier post, if you don’t understand why.

The problem with OFFSET though, is that it is what is known as a “volatile” function. This means that it always has to be recalculated when any cell in the spreadsheet changes – as it does not specify a range that it is dependent on, therefore does not know whether a change might affect its result.

INDEX however looks at a defined range, making it significantly more efficient, and in its simplest form can be used to replace both of these examples of OFFSET.

For a range the width of a single cell (as in our example), INDEX only needs two arguments to return the current month’s sales:

=INDEX($B9:$M9,$B$6)

This returns the value of the cell in position B6 in the range B9:M9.

If $B$6 is 3, this will return the value in cell D9, being the third cell in the range B9:M9.

To do the cumulative calculation, we can use the same INDEX function to return the end of  a SUM range, while fixing the start:

=SUM($B9:INDEX($B9:$M9,$B$6))

Again, if B6 contains 3, then this returns the sum of the range B9:D9.

In both cases, these will only recalculate if a cell in the range B9:M9 is edited. In a complex spreadsheet with many calculations, this can make a huge difference to calculation times.

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: Controlling what is printed from a sheet

From the Not Just Numbers blog:

One of the challenges that many Excel users face, is ensuring that the printed version of a spreadsheet looks as good as it did on the screen.

There are a few simple things that you need to know to help to organise what actually gets printed and how it is spread across pages.

I will cover the first of these today, and revisit some of the others in future posts.

Today we will look at how to determine how much of the sheet is actually printed.

Left to its own devices, Excel will print all of the used area on the sheet, Specifically, it will print the whole area from cell A1 to the rightmost column and the last row that are not empty.

This may not be what is required, and it is easy to change. Simply highlight the area that you do want to print, then go to the Page Layout ribbon, click the Print Area icon, and select Set Print Area.

You can even select multiple ranges (holding down the Control key, while you select the subsequent ranges) which Excel will print on different pages.

For example, you may have a Profit & Loss and Balance Sheet alongside each other on one worksheet. Just highlight the area of the Profit and Loss (say A1:H100) and then hold down the Control key while selecting the Balance Sheet range (say J1:P80) and Set Print Area as described above.

Once a Print Area has been set in this way, you can see (and edit it) using the Name Manager on the Formulas ribbon. You will see all of the Print Areas in the workbook listed there and (scope to their particular worksheet). You can then edit these ranges like any other.

You can even make them a dynamic range using functions like OFFSET and INDEX, so that the area that gets printed is determined by values in the workbook.

A particularly useful technique is to combine this ability to set a dynamic Print Area with a formula to determine the last row of data. I explained a formula to do this in this earlier post.

Let’s say we put this formula in a cell that we name LastRow.

If we want the print area to be columns A to J but the height of the print area to flex to the amount of rows occupied, we can enter the following as the Print Area (in the Names Manager):

=OFFSET($A$1,0,0,LastRow,10)

This will print a range starting at A1, with a height of LastRow, and a width of 10 (A to J is 10 columns).

Free Excel Dashboard Webinar

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: An easier way to change cell colours

From the Not Just Numbers blog:

Before I begin, I would like to wish a Happy New Year to all of my readers and subscribers – as this is my first post of 2016.

I am starting the year in humble mode, as I have had something very simple pointed out to me that I can’t believe I had never spotted, despite it being right under my nose!

In my last post of 2015, I showed you some code to swap one cell colour for another throughout a worksheet. I then received a comment from a reader that I only know as Jim, pointing out that Excel already has a very simple way of doing this!

It can in fact be done using Find and Replace.

This amazed me because I use Find and Replace all of the time and didn’t know you could do this!

It is simple as this:

  1. Highlight the range which you want to apply the changes to
  2. Click Find and Select (the binoculars icon) on the Home Ribbon and choose Replace from the dropdown menu
  3. Don’t enter anything in the Find or Replace boxes, but click the Format button next to the Find box and on the Fill Tab, select the colour that you wish to change
  4. Click the Format box next to the Replace box and on the Fill Tab, select the new colour that you wish to swap for the colour you selected above
  5. Click Replace All
You can even start with the colour of an existing cell, using the dropdown on the format button, however be sure to remove any other formats other than Fill colour.
The thing that really shocked me is that these two big Format buttons have been right there in front of me every time that I’ve used Find and Replace since Excel 2003! And that’s a lot of times!
In 2016, I am going to try to make sure that I constantly keep my eyes open for new ways to do things in Excel, instead of just relying on what I think I already know! And thanks again, Jim.

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: Merry Christmas with a quick macro to swap one colour for another

From the Not Just Numbers blog:

First of all I would like to wish all of my readers and subscribers, a very Merry Christmas and a Happy 2016.

I know we all work hard, and I hope, like me, you all get a chance to spend some time with those you love in the coming days, whether Christmas is a festival you celebrate or not.

One hassle I sometimes have when building spreadsheets for others is changing colours.

The spreadsheet may work perfectly, but the end user might not like the colours I have chosen. This isn’t too much of a problem if we are talking about large blocks of colour, but it can be a time-taking process, if I have used yellow to denote input cells throughout the whole worksheet, and the client wants orange, for example!

When this happened recently on a particularly complex spreadsheet, I decided to write a little macro to help, which turned out to be pretty straightforward and does the job in seconds.

Here is the code of the macro.

Sub ColourSwap() 

Dim Source As Variant
Dim R As Integer
Dim G As Integer
Dim B As Integer
Dim NewColour As Variant
Source = ActiveCell.Interior.Color
If MsgBox(“Switch to no colour?”, vbYesNo) = vbYes Then
NewColour = 0
For Each cell In ActiveSheet.Cells
If cell.Interior.Color = Source Then cell.Interior.ColorIndex = NewColour
Next
Else
R = InputBox(“R?”)
G = InputBox(“G?”)
B = InputBox(“B?”)
NewColour = RGB(R, G, B)
For Each cell In ActiveSheet.UsedRange.Cells
If cell.Interior.Color = Source Then cell.Interior.Color = NewColour
Next
End If 

End Sub

The easiest way to include it in your spreadsheet is to hit Alt-F8 and type the name you want to call the macro in the box at the top of the dialog. I have called it ColourSwap. Click create and you will see the green sections above already showing in the window (with your chosen name replacing ColourSwap). Just paste the yellow section in between.

You can run the macro by hitting Alt-F8 again, selecting it and choosing Run. If you prefer, you can click options instead of Run, and assign a shortcut key to run it in future.

The macro works as follows, and is applied to a single worksheet at a time.

 

  1. Click on one of the cells that contain the colour that you wish to swap;
  2. Run the Macro
  3. You will be asked if you wish to “Switch to no colour?”, if you select “Yes”, then all of the cells on that worksheet that are the same colour as the cell you selected, will have any Fill Colour removed. This is the same as choosing No Fill if you were colouring the cell manually.
  4. If you select “No”, you will be faced with 3 prompts, requesting the R, G and B values for the colour you wish to swap to. Once you enter these, all of the cells on the worksheet that are the same colour as the cell you selected, will be filled with this new colour.
NB: The macro only checks the Used Range of the worksheet, so will not change any coloured cells below, or to the right of the last populated cell on the worksheet. This is to save time, as it can take quite a while to loop through every cell, when this is not necessary. If (for some reason) you have coloured cells outside of the Used Range, then these should be very easy to change manually, as they will almost certainly be in a large block.
Note that if you wish to save the Macro with the spreadsheet, you will need to save the Workbook as Macro-enabled Workbook, however this will usually be unnecessary, as once the colours have been changed, the macro is no longer needed, so that you can let it save without the macro.
I hope you find this useful, and could maybe use it to make some tired old spreadsheets look a bit more festive!
Merry Christmas!

 

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: How many calendar months does a date range affect?

From the Not Just Numbers blog:

This week I responded to a client request for a formula that seemed straight-forward, but it took a few emails backwards and forwards to establish exactly what was required.

My answers at each stage, provide a number of alternative versions of what appear to be the same thing – but aren’t!

The question itself was essentially “How do I calculate the number of months between two dates?”

My first response to this question used the DATEDIF function as featured in this earlier post.

Assuming that the start date is in cell A1 and the end date is in cell A2, then:

=DATEDIF(A1,A2,”M”)

will return the number of WHOLE months between the two dates.

My client then said that they wanted to always round up the number of months.

I then used the “MD” argument of a DATEDIF to identify the remaining days after calculating the whole months, so that I could use and IF statement to add 1 if this remainder was greater than zero:

=DATEDIF(A1,A2,”M”)+IF(DATEDIF(A1,A2,”MD”)>0,1,0)

Finally, it transpired that what was really required was the number of calendar months touched by the date range, e.g. if the start date was 31st January 2015 and the end date was 1st February 2015, the answer should be 2, as both January and February feature in the date range (with the same dates, our first example would return zero, as there are no whole months and our second would have returned 1, as we rounded the 2 days up to a whole month).

This required a completely different approach, by using the month function to pull out the month from each date, and the year function to pull out the year. The answer would then be the difference between the month numbers, plus 1, plus 12 * the difference in the years, i.e.

=(MONTH(A2)-MONTH(A1)+1)+((YEAR(A2)-YEAR(A1))*12)

Depending upon your specific needs, any one of these formulae might be correct for your requirement!

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: An introduction to dynamic ranges

From the Not Just Numbers blog:

A few months ago I wrote a post  introducing the use of ranges in Excel:

Excel Tip: A short introduction to named ranges

In that post I alluded to dynamic ranges but didn’t really say much about them, so I thought I would expand a little on the subject now.

As the name suggests, dynamic ranges are ranges that are not fixed. The range referred to varies based upon either the cell in which the reference is used or a variable (or variables) referred to in a formula, or both.

If we go to name a new range using the Name Manager on the Formulas ribbon (if you need a refresher on this, please visit my earlier post), and in the “Refers to” box, we highlight a range, then by default this range is absolute (Excel automatically inserts the dollar signs to fix the row and column references).

So, if we type “Test” in the Name field and delete the contents of the “Refers to” box, then click in cell A1 of Sheet1 (while still in the “Refers to” box), Excel populates the “Refers to” box with:

=Sheet1!$A$1

This means that if we refer to the range “Test” anywhere else in the workbook, it will look at the contents of cell A1 of Sheet1. This is a normal (fixed) range.

Now let’s create a dynamic range.

We will follow the same process to create second range, but this time, ensure that cell B1 is selected before we start. Again create a new range in the Name Manager but call it Test2 this time. Delete the contents of the “Refers to” box again, then, again, click in cell A1. This will populate the “Refers to” box, as before, with:

=Sheet1!$A$1

This time though, before clicking OK, use the F4 key to remove the dollar signs.

The “Refers to” box should now read:

=Sheet1!A1

This is now a relative reference, relative to the cell we had selected prior to defining the range (B1). The range “Test2”, will now refer to the contents of the cell immediately to the left of the cell that you use it in (as A1 is the cell immediately to the left of B1).

Try typing the formula =Test in multiple cells. This will always return the contents of cell A1. But type =Test2 in any cell, and it will return the contents of the cell to its left. “Test2” is therefore a dynamic range – the cell(s) it refers to change depending on where it is used.

Note that this is not just the case with a single cell, we can refer to a number of cells.

Let’s take an example. Let’s say that we have a 12 month budget, with the 12 monthly values in columns B to M. Click in cell N1 and name a new range in the Name Manager called “FullYear” and type the following into the “Refers to” box:

=Sheet1!$B1:$M1

We can either type this in, or as before, highlight the cells B1 to M1, but then use the F4 key on each of the references to remove the dollar from the row reference.

Note that I have left the dollars on the column references. This means that the row will change, but the columns will stay fixed. This means that we can use the formula =SUM(FullYear) and it will always sum columns B to M of the current row.

Sticking with this same example, we can use the OFFSET function to extend this further and allow us to have dynamic ranges for the current month’s balance, and the year to date balance.

If we store the number of the current month (1 to 12) in cell P1, then we can name a range called “MonthBalance” by clicing in cell N1, and creating the range as before, but typing the following formula in the “Refers to” box:

=OFFSET($B1,0,$P$1-1)

Note the use of the dollars, The column of B1 is fixed but the row is left relative, whereas P1 is entirely fixed.

This will return the contents of the cell P1-1 cells to the right of column B, on the same row. So if the month number entered in P1 is 3, P1-1 =2. As column B is the month 1 balance, 2 columns to the right in column D is the month 3 balance!

So we can enter =MonthBalance in any cell and it will return the current month’s balance from that row.

We can define the range “YTD” as:

=OFFSET($B1,0,0,1,$P$1)

This will return a range P1 wide and 1 row high starting in column B of the current row, i.e. all of the months to date. As this will usually be more than one cell, you will need to use SUM to total the range.

We can now use =SUM(FullYear), =MonthBalance and =SUM(YTD), to give us these totals on any row of the sheet. In addition, MonthBalance and SUM(YTD) will change depending on the month number entered in P1.

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: Return the formula text from a cell, rather than its value

From the Not Just Numbers blog:

Just a short little tip this week, due to a hectic diary.

When you reference a cell in Excel, you will get its value, but what if you want to return the formula itself?

Excel, as usual, provides a way to do this.

NB: This function is only available in Excel 2013 onward. If you need this functionality in earlier versions of Excel, Bill Jelen has a simple video on how to create a User-defined function to do it.

Let us say that cell A1 contains:

=SUM(B1:B10)

If we enter the following into cell C1:

=A1

then cell C1 will show the same number that A1 shows, i.e. the sum of the numbers in cells B1 to B10.

What if we wanted to see the actual formula in cell A1?

We can use the FORMULATEXT function in C1:

=FORMULATEXT(A1)

This will return the text:

=SUM(B1:B10)

This may be useful for its own sake (for example, to show how numbers are calculated alongside the numbers themselves), or to return the text of the formula, so that you can manipulate it.

A couple of things to note:

  • FORMULATEXT will return #N/A if:
    • the cell does not contain a formula
    • the formula is more than 8,192 characters!
    • worksheet protection doesn’t allow the formula to be shown
    • it refers to an external workbook that is not open.
  • If the range argument is more than one cell, it will return the formula in the top left cell of the range.

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: Show negative numbers in brackets

From the Not Just Numbers blog:

Working with accountants, one of the requirements I often get asked for, is to show negative numbers in brackets.

Surprisingly, this is not one of the standard number formats in Excel, not even if you choose the Accounting format!

Fortunately, however, this can be remedied using a custom number format.

It is usually easier to start with a format that is close to what you want. We will start with the Accounting format, to 2 decimal places, and no currency symbol.

To select this, right-click the cell, choose Format Cells and, on the Number Format tab, selecting Accounting. In the information to the right, select 2 decimal places and None (for the currency symbol).

Click OK to store this as the number format for that cell (or the range of cells selected).

Now follow the same sequence again, but this time choose Custom as the Number Format. You will see the code for the existing format (as previously selected) in the box at the top of the section on the right:

_-* #,##0.00_-;-* #,##0.00_-;_-* “-“??_-;_-@_-

We will edit this code to give us our brackets.

The first thing that we need to be aware of is the different sections of the code. This format uses the maximum four sections, each section being separated by semicolons.

The sections are as follows:

  1. Positive Numbers
  2. Negative Numbers
  3. Zero
  4. Text
It is not necessary to have all of these.  Any sections not included will follow the formatting set in section 1.
In this case, however, we have all four sections, but we are only interested in changing the first three – in particular Section 2 for negative numbers.
From above, we can see that the current formatting for negative numbers as follows:
-* #,##0.00_-
The first character is simply the minus sign.
This is followed by an asterisk (*) and a space. The asterisk tells Excel to repeat the character that follows it, to fill the remainder of the cell. As this is followed by a space, this tells Excel to pad out the area between the minus sign and the number with spaces, so that the whole cell is occupied. This is why the minus sign is shown on the far left in the Accounting format.
The #,##0.00 tells Excel that we want to see the number to two decimal places, with commas to mark thousands.
Finally, the _- creates a space the width of the minus sign. The underscore (_) symbol, inserts a space the width of the character that follows it.
To edit this to show our brackets, we can do the following:
  • Delete the leading – sign, as the brackets will denote the negative
  • Place an opening bracket immediately before the number, assuming that we want the opening bracket to be placed after the leading spaces
  • Replace the _- with a closing bracket. We no longer need the minus width space at the end, but we do want a closing bracket here
The new negative format should now look like this:
* (#,##0.00)
This is not the end of the story, however. We want to also slightly tweak the positive and zero sections, so that they line up correctly with the bracketed negatives.
The positive section currently looks like this:
_-* #,##0.00_-
We need to ensure that we have a space the width of a bracket in the same places that we have the brackets in the negative number. We also don’t need the space the width of a – at the start and end, as these were removed from the negative.
The new positive format looks like this:
* _(#,##0.00_)
Finally, we need to make the same changes to the zero format which currently looks like this:
_-* “-“??_-
But, applying these changes, becomes:
* _(“-“??_)
So, the complete new number format is:
* _(#,##0.00_);* (#,##0.00);* _(“-“??_);_-@_-
We could trim this down even further if we like.
We don’t really require the leading spaces, as there is nothing to the left of them, so we could remover the Asterisk and the space at the start of the positive, negative and zero sections.
We also, don’t really need the text section, as this was only adding the leading space to coincide with the minus on the negative numbers, as well as the trailing space that was against all of the numbers.
Our streamlined format now looks like this:
_(#,##0.00_);(#,##0.00);_(“-“??_)
And if you don’t care how we got here, you can just select Custom Format and paste the above code in!

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: Display current sheetname

From the Not Just Numbers blog:

Sometimes it can be very handy in a spreadsheet with multiple sheets, to show the sheet name in the sheet itself.

Say you have a sheet for each salesperson and new sheets are regularly being added and you name the sheets with the salesperson’s names and want the same name to appear in the heading on the sheet. This is particularly important when printing the sheets as the worksheet name will not be visible.

You could, of course, type the same name in the header as the name of the sheet, but this has a few disadvantages:

  1. It’s twice as much work
  2. You may forget, and have a different salesperson’s name on the printed reports as is being used to pay them for example. This kind of inconsistency can lead to all sorts of problems!
Fortunately, it is relatively easy to get at the sheet name in a formula.
We can use the CELL command to do most of the work. This allows you to pull information about the current cell. In this case we are going to use it to pull the file path (including the sheet name). This is done by entering “filename” as the info type argument in the CELL command as follows:
=CELL(“filename”)
This will show something like:

 

C:\Users\Glen\Documents\[MySpreadsheet.xlsx]SheetName
where MySpreadsheet.xlsx is the name of the spreadsheet and SheetName is the name of the sheet that contains the CELL function above.
As we just want the sheet name, we can use the fact that the workbook name is enclosed in square brackets as follows:
=MID(CELL(“filename”),FIND(“]”,CELL(“filename”))+1,999)
This earlier post gives more information on both the FIND and MID functions.
Essentially, this returns the 999 characters starting at the position after it finds the “]” (the +1 ensures that we don’t start until the character after the “]”). I have simply used 999 to ensure that all of the characters after the “]” are returned. It will not return any extra characters, so will just return all of the characters after the “]”, i.e. the sheet name!

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.

Excel Tip: Make it easy to enter the arguments for a function

From the Not Just Numbers blog:

I have said this many times before, but one of the things I like most about working with Excel is that there is always something new to learn.

I don’t just mean learning new features as they are added. I mean learning things that have always been there that you didn’t know about!

A blog post on another Excel expert’s blog taught me a really simple one the other day, that I’m not sure how I’ve missed!

Reading a post on Charley Kyd’s ExelUser blog on Excel’s Five Annuity Functions, he revealed a simple feature that I had never come across, but could be useful when entering any function in Excel.

Did you know that you can start typing any function and then press Ctrl-Shift-A for excel to fill it in with the names of the arguments, which you can then simply replace with the actual arguments.

For example, if you type:

=VLOOKUP

and press Ctrl-Shift-A, Excel puts the following into the formula bar:

=VLOOKUP(lookup_value,table_array,col_index_num,range_lookup)

You can then replace these argument names with the arguments for your particular scenario.

Alternatively, you could even leave it as is and name the cells and ranges that hold the arguments with these argument names as range names.

i.e. name the cell that contains the value you want to look up, lookup_value and the range that contains your lookup table table_array, etc.

I’m not sure I would use the range naming approach, not least because you could then only use the function once in your spreadsheet!

Using Ctrl-Shift-A to give me a skeleton to enter the function arguments does sound useful though.

If you enjoyed this post, go to the top of the blog, where you can subscribe for regular updates and get two freebies “The 5 Excel features that you NEED to know” and “30 Chants for Better Charts”.