2008 September | Automate Excel

Automate Excel

Sep 30

To change the colour of a cell we can use:

Cell.Interior.ColorIndex = Num

Where:
• Cell is the cell reference
• Interior – refers to the colour of the actual cell colour (The interior property)
• Colourindex is a value between 1 and 56 for one of Excel’s 56 predefined colours

And Num is the number colour assigned to the cell. However, it isn’t always easy to remember which number represents which colour. The following subroutine changes the cell colour based on the row number. So for example row 3 will have colour 3 etc.

As there are 56 preset colours in Excel, this means that cells 59, 115 will have the same colour as the cell in row 3:

Option Explicit
Private Sub CommandButton1_Click()
Colour_Range (Sheets("Sheet2").Range("A1:A2000"))
End Sub
Sub Colour_Range(Cell_Range As Range)
' Will Colour each cell in range
Dim Cell
For Each Cell In Cell_Range
Cell.Interior.ColorIndex = Cell.Row Mod 56
Cell.Offset(0, 0).Value = Cell.Row
Next
End Sub

The routine is activated by a click event.

To download the .XLSM file for this tutorial, please click here.

Sep 30

The standard Vlookup function can be used to find a value within a table:

And we would use VLOOKUP like so:

VLOOKUP(A1:10,”Dog”,2,FALSE) to give the value 30.

However, in this list we see that Dog occurs 3 times. The standard VLOOKUP function will only return the value associated with the first item in this list. It won’t return the 125 or 9,250 with the 2nd or 3rd instance of “dog” in this list.

The following function allows us to specify a range, an expression to be searched for, and the instance and then return the corresponding value:

Function Find_nth_Occurrence(Column_Range As Range, Expression As String, Occ As Integer) As Double
Dim Cell
Dim Occurrences_to_date As Integer
Find_nth_Occurrence = 1000000
Occurrences_to_date = 0
For Each Cell In Column_Range
If Cell.Value = Expression Then
    Occurrences_to_date = Occurrences_to_date + 1
    If Occurrences_to_date = Occ Then
      Find_nth_Occurrence = Cell.Offset(0, 1).Value

    End If
End If
Next Cell
End Function

The main difference between this and the standard VLOOKUP function is that in this case, the range is the only the range of labels – not the entire data range.

The following is a subroutine that calls this function based on the click event from a command button. It looks in the range A1:A8 on Sheet2, for the 3rd instance of the word Dog:

Private Sub CommandButton1_Click()
Dim Answer As Double
Answer = Find_nth_Occurrence(Sheets("Sheet2").Range("A1:A8"), "Dog", 3)
MsgBox AnswerEnd Sub

The variable “Answer” stores the result of the function – which is then displayed in a Msgbox on the screen:

However if the word can’t be found in the list or the frequency does not occur e.g there isn’t a 5th instance of the word “Dog”, then the value of 1,000,000 is returned :-

Answer = Find_nth_Occurrence(Sheets(”Sheet2″).Range(”A1:A8″), “Dog”, 5)

Or

Answer = Find_nth_Occurrence(Sheets(”Sheet2″).Range(”A1:A8″), “Horse”, 2)

Sep 30

This example shows how Excel and VBA can interact with each other. VBA will be used to generate function values over a given range. The answers will then be stored within an Excel workbook and used to produce a graph.

This could be done entirely with Excel without the use of VBA. But if the formulae was particularly complicated then the Excel expression would be difficult to decipher. Instead, we just pass the function arguments to a VBA function. The function then evaluates the expression and returns the answer to Excel.

In this case our function will be a “saddle”:

X^2 – Y^2

Or

X*X – Y*Y

So we set up our x and y values in Excel:

Our function is called Demonstrate_Function and will have two arguments (x and y). The following is the code for this function:

Function Demonstrate_Function(x_arg As Long, y_arg As Long) As Long

'Dim Demonstrates purpose of function interacting with Excel
'The answer will be stored in "Demonstrate Function"

'the function will just take the difference between the squared values of x and y

Demonstrate_Function = (x_arg * x_arg) - (y_arg * y_arg)

End Function

Note that this code must be inserted in a module. So to call the function with an x-value of 1 and a y value of 2 we put the following code into a cell:

T3= Demonstrate_Function (1,2)

which gives a value of -3.

And we now put this formulae into all the cells in our range:

However to see the function more clearly we can plot a surface chart:

Sep 26

The following code will populate a given range with a random number between 0 and 1000:

Sub Randomise_Range(Cell_Range As Range)
' Will randomise each cell in Range
Dim Cell
'Turn off screen alerts
Application.ScreenUpdating = False
For Each Cell In Cell_Range
Cell.Value = Rnd * 1000
Next Cell
Application.ScreenUpdating = True
End Sub

The code “Application.ScreenUpdating =FALSE” and “Application.ScreenUpdating = TRUE” serve to turn off and turn on screen alerts – making the code much faster to run.

It can be set up via a click event, with the main routine specifying the range:

Private Sub CommandButton1_Click()
Randomise_Range (Sheets("Sheet3").Range("A1:T8000"))
End Sub

So this case, cells A1:T8000 on sheet 3 are populated with random numbers – once the command button 1 is clicked.

Download the .XLSM file here

Sep 26

The following VBA function will check if a given date is between two other dates and if so, it will return the value TRUE. If the date is not in between the dates, then it will return the value FALSE.

Function Compare_Dates(Start_Date As Date, End_Date As Date, Other_Date As Date) As Boolean
' Boolean Function to compare dates
'Will return TRUE only when Other_Date is between Start_Date and End_Date
'Otherwise will return FALSE
'Set outcome to FALSE - default value
Compare_Dates = False
'Compare Dates
If ((Other_Date >= Start_Date) And (Other_Date <= End_Date)) Then

'If Other Date is between Start and End Date then set to true
Compare_Dates = True

End If
End Function

The function has three arguments:
• Start_ date – the earliest allowable date
• End_ Date – the latest allowable date
• Other_Date – the date being compared

The function must be in an Excel module. It can be run from an Excel Workbook e.g:

A4= Compare_Dates(21-06-2003,12-02,2008,15-09-2008)
A3 =Compare_Dates(A1,A2.A3)
A1= Compare_Dates(13-03-2005,18-08-2005,A6)
So Compare_Dates(25-04-2007,12-07-2008, 23-06-2006) will give the value TRUE as 23-06-2006 is between 25-04-2007 and 12-07-2008.

Likewise Compare_Dates(19-07-2003,12-12-2001,12-08-2008) will return FALSE as 12-12-2001 is NOT between 19-07-2003 and 12-08-2008

Download .XLSM function here

Sep 26

It is quite easy to work out the average of a series of numbers:


We just use the average function in Excel. However what happens if we want the average of only the NON – ZERO Values.  The function COUNTIF will count up the cells in a range that meet a criteria:

COUNTIF(Range, Criteria)
The criteria must be placed in quotes –so if our criteria is greater than 0 we need the phrase “>0”. In this case our criteria is not equal to zero.  Remembering that the average of  a series of numbers is their total divided by the total number we have:

Where the “<>0” allows us to count up the non zero values in the range:

Sep 20

Imagine that we have a table of data such as:

And then we do a VLOOKUP on a city that isn’t there we get an N/A error:

This is not much of an issue if we have only a single N/A error. However, if we have several N/A (each arising from a separate VLOOKUP) in a table then it can look rather unsightly. In addition any totals that involve these cells also result in the value N/A. In short the N/A error can propagate through the entire workbook:

To get around this, Excel has the function ISNA which allows us to check whether or a condition or a cell has the value N/A. It is usually used as part of an IF statement:

B1 =IF (ISNA(A1), 0,A1)

i.e if the cell A1 has the value ISNA then the cell B1 takes the value 0 otherwise it has the value in A1.

Or if we have a VLOOKUP formulae, we can check whether or not it evaluates to NA using the same approach. If does then we take the value 0 otherwise we take the value returned by the VLOOKUP value:

=IF(ISNA(VLOOKUP(B18,B6:C13,2,FALSE)),0, VLOOKUP(B18,B6:C13,2,FALSE))

And if this approach is adopted in the individual rows in the above table we have:

Which is much more presentable and the totals now evaluate sensibly.

Sep 20

Imagine that we have some Sales Figures for a company:

And that we wish to find the Total figures for the year to date. We can add a drop down like so:

So that we can specify the current month. Hence we now want to work out the year to date for March. The simplest format would be to have a formulae that extended across the range:

And then we would just change the formulae every month.

However Excel permits another approach. We could set up a dynamic range whose size varied on the month that we are in. As we change the month in the drop down then the size of the range changes.
So for the month of March the range is 3 columns long, and for the month of June it would be 6 months along.

The size of the range is governed by the month. One way of formulating this is to use the Month function:

=Month(c8)

Where c8 is the cell address of our drop down. However the method that is preferred is to use the MATCH function to determine the position of the current months in all the months in our report:

MATCH(c8,$c$3:$j$3,0)

Where:
• c8 is the cell address of the current month
• C3:J3 is the address of all our months
• 0 is to ensure an exact match

Now we can specify the size of our dynamic range by the OFFSET function which has 5 arguments:
=OFFSET(reference, rows, cols, height, width)

Where:
• Reference is the top left hand corner of our dynamic range – cell C5 – the first cell that we want to sum
• Rows – the number of rows down from our base cell – this is 0
• Cols – the number of cols across from our base call – this is 0
• The width of our dynamic range – which is 3 in this case. However as we wish the range to vary by month we will put our MATCH formulae here
• This is the height of our dynamic range which is 1

So our OFFSET formulae is:
= OFFSET(c5,0,0,MATCH(c8,$c$3:$j$3,0),1)

Finally we need to tell Excel to SUM this to give the complete formulae as:
= SUM(OFFSET(c5,0,0,MATCH(c8,$c$3:$j$3,0),1))

We have:

Now if we change the month in the dropdown, the correct year to date figure flows through:

As this is an automatic update this approach has the following advantages:
• There is no need to change the formulae each month
• As there are less formulae changes, less scope for error
• The spreadsheet can be used by somebody who has limited Excel knowledge – they can just change the dropdown and not be bothered by formulae

Sep 20

The following VBA function counts the number of words in a string:

Function Number_of_Words(Text_String As String) As Integer
'Function counts the number of words in a string
'by looking at each character and seeing whether it is a space or not
Number_of_Words = 0
Dim String_Length As Integer
Dim Current_Character As Integer

String_Length = Len(Text_String)

For Current_Character = 1 To String_Length

If (Mid(Text_String, Current_Character, 1)) = " " Then
    Number_of_Words = Number_of_Words + 1
End If

Next Current_Character
End Function

It is worth noting a couple of points:
• This code must be inserted in a Workbook Module – from the VBA pane, click on Insert and then module

• The function can be called from an excel workbook cell either with an either explicit text or cell reference as an argument:
A3 = Number_of_Words(“Pig Dog Cat”)
A4 = Number_of_Words(D1)

The function works by traversing the length of a string and seeing if the next character is a space and if so it adds one to the number of spaces in the string.

Sep 13

The following code is a subroutine that will get the names of all the files that are present in a directory path:

Sub List_All_The_Files_Within_Path()

Dim Row_No As Integer
Dim No_Of_Files As Integer
Dim kk25 As Integer
Dim File_Path As String

File_Path = "C:\My Documents"

Row_No = 36

'Lists all the files in the current directory

With Application.FileSearch
.NewSearch
.LookIn = File_Path
.Filename = "*.*"
.SearchSubFolders = False
.Execute

    No_Of_Files = .FoundFiles.Count

    For kk25 = 1 To No_Of_Files
       Worksheets("Sheet1").Cells(kk25 + 5, 15).Value = .FoundFiles(kk25)

    Next kk25

End With

End Sub

It will write the filenames to Sheet1 in column O – starting at row 36.

Download the Excel file here

Sep 13

The VBA Routine below allows the user to enter a string, and is then presented with the same string backwards. For example “Monday” becomes “yadnoM”:-

Option Explicit

Private Sub CommandButton1_Click()

'Define Variables

Dim Original_String As String
Dim Reversed_String As String
Dim Next_Char As String

Dim Length As Integer
Dim Pos As Integer

'Get the Original String

Original_String = InputBox("Pls enter the original string: ")

'Find the revised length of the string

Length = Len(Original_String)

'Set up the reversed string
Reversed_String = ""

'Progress through the string on a character by character basis
'Starting at the last character and going towards the first character

For Pos = Length To 1 Step -1

    Next_Char = Mid(Original_String, Pos, 1)
    Reversed_String = Reversed_String & Next_Char
Next Pos

MsgBox "The reversed string is " & Reversed_String

End Sub

The main features of the code are :-

• It needs a command button to activate the code – on the click event
• The following variables are set up :-

o Original_String – the original string that will be reversed (“Monday”)
o Reversed_String – the reversed string (“yadnoM”)
o Next_Char – the next character in the string that will be reversed
o Length – the length of the string
o Pos – the current position in the string

• An InputBox to capture the string. This is stored in the variable “Original String”
• The Length of the String is calculated using the LEN function and stored in the variable Length
• A FOR…NEXT loop is set up to go through the string starting at the last character and working backwards one character at a time
• The next character in the original string (working backwards) is then added to the reversed string
• This loop is iterated until we have traversed the entire length of the string
• The reversed string is displayed in a MsgBox.

Download the Excel file here

Sep 13

Excel lets us control things through events. This article isn’t a detail discussion on what events are or their features. Instead it gives an example of a WorkBook Event. These are events that are held at the workbook level rather than a particular worksheet.

Through VBA we can control what happens at certain events such as before printing or before saving. One common problem that I face is that a number of people I work with don’t like files with Freeze Panes on them.

So in this article, we will put together some code that will check if Freeze Panes is on and if so, it won’t save the file. This means that I have to save it without freeze panes – keeping my colleagues happy !!

The most important thing about workbook events is that they should be saved in the correct place – at the workbook level.

To access the workbook level, follow the steps below:

1. Right click on an Excel workbook - view code:

2. This will bring up:

3. Double click on “This Workbook” and then select “WorkBook” from the first drop down on the left hand side:

We see that the value on the left hand side has now changed to “Open” – with some code for the Workbook Open Event. This code will let us determine what happens when the workbook opens for the first time.

However we want to control what happens when we save the workbook. So change the right hand drop down to “Before Save” . The screen will now look like:

We now insert the following code after the declaration:

If ActiveWindow.FreezePanes = True Then

    MsgBox "Freeze Panes is on - File is NOT SAVED"

    Cancel = True

End If

So that the complete code now looks like:

Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)

If ActiveWindow.FreezePanes = True Then

    MsgBox "Freeze Panes is on - File is NOT SAVED"

    Cancel = True

End If

End Sub

Now save the file and THEN activate Freeze Panes in any window. Then – RESAVE the file. A msgbox will appear stating that “Freeze Panes” is on – and the file is not saved.

Indeed the file will not save until Freeze Panes is removed.

Sep 12

Imagine that we have 20,000 rows of data in an Excel spreadsheet:

However, what about if you wanted to cut this data down such as take every 5th row ? This article shows how it can be done. The Row() function gives the number of each row:

The mod function allows us to perform modulo arithmetic:

Mod(Number,Divisor)

Gives the remainder when “Number” is divided by “Divisor”. So for example:

Mod(28,5)

Will give 3 the remainder when 28 is divided by 5.
So we can look at the row number and see what happens when we perform modulo arithmetic on it:

IF(Mod(Row(),5)=0,1,0)

i.e consider the remainder when the row number is divided 5. If the remainder is 0 then put a 1 in the cell otherwise put a zero. For convenience I have hardcoded the row numbers in the above table . Now we insert additional column to work out when this happens. The formulae will be the modula formulae as above:

We see that rows that have row numbers that are divisible by 5 have modulo 1. If we now FILTER the data to show only the 1’s:

If we now select Visible Cells only and then copy this data only, we have our subset of our data.

Sep 12

The following tutorial will describe how to create a chart in a cell like the one displayed in the table above under the “Trend” column.

The chart is created using a function called “CellChart”. You would enter it in Excel like any other standard function i.e. SUM, AVERAGE or VLOOKUP etc. This function is called a “User Defined Function” and is not a standard function available within Microsoft Excel. It must be created by the user using VBA.

When entered into Excel, the CellChart function looks like this:

Taking a closer look at the CellChart function, the range for the chart is defined in the first part of the function, C3:F3 in the example above. Next the color of the chart is defined, 203 using the example above.

Now for the VBA stuff

1. Enter the VBA project window by right clicking on a sheet name and selecting “View Code” or by selecting “ALT, F11”.

2. On the right hand side, right click on your project name and select inset “module”.

3. Copy and paste the following code into the new module you just created:

'Creates a new function called Cell Chart
Function CellChart(Plots As Range, Color As Long) As String

'Defines the variables that will be used later on in the code
Const cMargin = 2
Dim rng As Range, arr() As Variant, i As Long, j As Long, k As Long
Dim dblMin As Double, dblMax As Double, shp As Shape

'The following calculates the plots to be used for the chart
Set rng = Application.Caller
    ShapeDelete rng
    For i = 1 To Plots.Count
        If j = 0 Then
            j = i
        ElseIf Plots(, j) > Plots(, i) Then
            j = i
        End If
        If k = 0 Then
            k = i
        ElseIf Plots(, k) < Plots(, i) Then
            k = i
        End If
    Next
    dblMin = Plots(, j)
    dblMax = Plots(, k)

 'The next piece of code determines the shape and position of the chart
     With rng.Worksheet.Shapes
        For i = 0 To Plots.Count - 2
            Set shp = .AddLine( _
                cMargin + rng.Left + (i * (rng.Width - (cMargin * 2)) / (Plots.Count - 1)), _
                cMargin + rng.Top + (dblMax - Plots(, i + 1)) * (rng.Height - (cMargin * 2)) / (dblMax - dblMin), _
                cMargin + rng.Left + ((i + 1) * (rng.Width - (cMargin * 2)) / (Plots.Count - 1)), _
                cMargin + rng.Top + (dblMax - Plots(, i + 2)) * (rng.Height - (cMargin * 2)) / (dblMax - dblMin))

 'Difines what happens if there is an error
            On Error Resume Next
            j = 0: j = UBound(arr) + 1
            On Error GoTo 0
            ReDim Preserve arr(j)
            arr(j) = shp.Name
        Next

        With rng.Worksheet.Shapes.Range(arr)
            .Group

            If Color > 0 Then .Line.ForeColor.RGB = Color Else .Line.ForeColor.SchemeColor = -Color
        End With

    End With

    CellChart = ""
End Function

Sub ShapeDelete(rngSelect As Range)

'Defines the variables that will be used later on in the code
    Dim rng As Range, shp As Shape, blnDelete As Boolean

      For Each shp In rngSelect.Worksheet.Shapes
        blnDelete = False
        Set rng = Intersect(Range(shp.TopLeftCell, shp.BottomRightCell), rngSelect)
        If Not rng Is Nothing Then
            If rng.Address = Range(shp.TopLeftCell, shp.BottomRightCell).Address Then blnDelete = True
        End If

        If blnDelete Then shp.Delete
    Next
End Sub

4. Click on the save button.
5. Click on the little Excel icon on the top right under the “File” menu to exit the VBA project window and to return to Excel

6. Enter the CellChart function into any cell as displayed above.
7. See the attached workbook for a working example of the above.

For further information on this type of in cell charting, please visit:

http://www.dailydoseofexcel.com/archives/2006/02/05/in-cell-charting/

Sep 6

Imagine that we have a series of steps that take a time to run (e.g they could be part of a manufacturing process) such as:

And we now want to calculate the duration of each step. We note that successive steps do NOT finish in chronological order.

For the purpose of this exercise we assume that no two events finish at exactly the same time.

The first thing to do is to determine the order in which the events occur. This can be done by using the RANK function:

The elapsed time will be the difference between the current and previous event finishing. So now we need to have the position of the previous item. However we need to ignore the first item as there is nothing before it:

The Excel function SMALL returns the smallest value from a range:

SMALL(Range, k)

We can use this to determine the time that the previous item finished. However once again, we need to ignore the item that finished first:

Where the formula in Column F is:

=IF(D5=1,0,SMALL($C$4:$C$13,E5))

- We check if it is the earliest finishing step – if so we return 0. Otherwise, we return the time that the previous event finished.

We then take the difference between the times in Column F and C to get the exact process times. However for the first item we will take the time that it finished:

Sep 6

The VLOOKUP and HLOOKUP functions are well known for looking up data in one dimension:

And then:

However what happens if we have a TWO dimensional array

And we want to find the value for Boats in Mar-08.  So we could add two drop downs to specify the mode of transport and the month that we need:

Excel provides a function called INDEX that allows us to return values from a 2d array:
INDEX(Array_Range, Row Number, Col Number)

Where
•    Array_Range  is the range in Excel of the two dimensional array – in this case $B$4:$H$7
•    Row Number  is the position in the list where we find the text “Boat”  - in this case is 1
•    Col Number is the position in the list where we find the month “Mar-08”

Of course the only thing left to do is to determine the Row and Column Number. This is done by using the MATCH function – which returns the position of a string within a range of values:
MATCH(“String”, Range,0) – will return the position of  “String” in the array “Range” and the 0 states that we want an exact match. So we are looking for the position of Boats in the range {Boats, Cars, Planes , Lorries} – which is 1. This will give the row number:

MATCH(B11,$B$4:$B$7,0)
And similarly for the column number
MATCH(C11,$C$2:$H2,0)
And then we combine all these into one function:
=INDEX($C$4:$H$7,MATCH(B11,$B$4:$B$7,0),MATCH(C11,$C2:$H$2,0))
To give the value of 79 for boats in March 2008:

Sep 5

Excel’s SUMIF formulae allows you to obtain the sum of a range of values that meet certain criteria. For example:

If we wanted to obtain the total number of Cars then we could use SUMIF:

=SUMIF(B5:B12,”Cars”,D5:D12)

and if we wanted to obtain the total vehicles in Cambridge we could use:

=SUMIF(A5:A12,”Cambridge”,D5:D12)

However what would we do if we wanted the total number of all the cars in Cambridge ? We can’t use SUMIF as it only allows for one criteria to be selected, and we have two (City and Vehicle Type). The solution is to use SUMPRODUCT:

=SUMPRODUCT(–(Criteria 1),–(Criteria 2), Summation Values)

where Criteria 1 and 2 are the data selection values (i.e City = “Cambridge” and Vehicle Type =”Cars” and the Summation Values are the values that are being summed (Column D – the numbers of vehicles).

=SUMPRODUCT(–($A$5:$A$12=”Cambridge”),–($B$5:$B$12=”Cars”),$D$5:$D$12)

Excel will go through each of the cells in the range A5:A12 and evaluate those that equal “CAMBRIDGE”. For those that do, it assigns the value “TRUE”. For those that do not equal “CAMBRIDGE”, it will assign the value “FALSE”.

The – is a Logical Operator within Excel and is nothing to do with the normal minus operator. This operator converts all “FALSE” values to 0 and “TRUE” values to 1.

This enables us to use SUMPRODUCT in this way to evaluate multiple criteria:

Sep 5
Ranking Values
icon1 Kaps | icon2 Formulas | icon4 09 5th, 2008| icon3No Comments »

Imagine that we have the following data:

And we want to find the people with the highest 3 marks. Note for this example, we will assume that there are no two people with exactly the same score.

The function RANK allows us to do this. It needs 2 arguments – the cell that we are comparing and the range over which we are comparing:

RANK(A7, A2:A20)

Will give us the ranking of Cell A7 in the range A2:A20. So if we apply to this to our formulae and copy down:

We see that the highest marks are Anthony, Mark and then Jordan – receiving 35, 30 and 28 marks respectively.

Note so far we have only determined the ranking of the names – not the actual names of the people. To do that we need to find the position of the ranking – i.e the fact that the 2nd largest value is on the 4th row of our data, and that the 4th largest is on the 6th row. This is achieved by doing the MATCH function:

MATCH(A2, A2:A10,0)

Will give us the position of contents of the cell A2 In the range A2:A10. So we can add another column to determine the position of the nth largest item:

And then we can set space on the workbook to display the three largest values:

And we state the position of the 3 largest items – using the MATCH function that we have just defined:

This will return the position in the list of the largest 3 items. We can then use in the argument of an INDEX function to return the name of the students with the 3 highest marks:

Sep 5
Double SUMIF
icon1 Kaps | icon2 SUMIF | icon4 09 5th, 2008| icon3No Comments »

Consider the following table of data:

If we want to find the total of all the Lorries then we could use the SUMIF function:

E25 = SUMIF(A5:A20,”Lorries”, E5:E20)
Like so:

And likewise we could total all the red vehicles:

=SUMIF(C5:C20,”Red”,E5:E20)

However what about if we wanted the total of all the YELLOw Vehicles in London ? There are in fact several ways of doing this. We will consider one for now and look at the others in later articles.
The simplest way of achieving this is to add another column which concatenates the City and Vehicle colour for each row, and then do a SUMIF across this new column:

D5 = A5 & “ “ & C5

The operator & allows us to Concatenate two strings. It is a shorter alternative to the function CONCATENATE. We are inserting a space “ “ between the strings in Column A and C – to make it more readable. So copying down we have:

And then we just use SUMIF on the new column:

=SUMIF(D5:D20,”London Yellow”,F5:F20)

We have that:
The total is 54,800 – the sum of 45,000 and 9.800.

As I mentioned that there are other ways of other doing this – and we’ll look at them in future articles.