Formula Forensics. No 007 – Sumproduct

Share

Facebook
Twitter
LinkedIn

One of the most asked questions within the posts and Forums at Chandoo.org is “How Does Sumproduct work ?”.

Rahul recently asked for an example in Excels Sumproduct Formula post;  Comment No. 55.

So today in Formula Forensics we will take a look at just that with a few worked examples.

Sumproduct

Excels help defines Sumproduct as:

So what are these arrays referring to:

An array in Excel can be :

A manual Array:     {10;20;30}

A Range:              A1:A3

A Named Range: MyRange1

Where MyRange1 is defined as a defined range in the Name Manager.

A Named Formula: MyRange2

Where MyRange2 is defined as a Formula returning a range in the Name Manager.

 

Lets look at each

You can follow along in the Example file on Sheet1

An Array

In C2 type: =SUMPRODUCT({10;20;30})

Excel will display 60, which is the Sum of the array elements =10+20+30

A Range

C7:          =Sumproduct(C4:C6)

Excel displays 60, which is the Sum of the cells from the range C4:C6 =10+20+30

A Named Range

In the Name Manager or Name Box define a Named Range

MyRange1:         =Sheet1!$C$4:$C$6

Then in C10 type:

C10: =Sumproduct(MyRange1)

Excel displays 60, which is the Sum of the range elements =10+20+30

A Named Formula

In the Name Manager define a Named Formula

MyRange2          =OFFSET(Sheet1!$C$3,1,0,3,1)

Then in C12 type:

C12:       =Sumproduct(MyRange2)

Excel displays 60, which is the Sum of the range elements from cells C4:C6 =10+20+30

 

You may be asking why use Sumproduct when we can use a simple Sum to add up 3 numbers?

The answer is to show you what Sumproduct is doing, it is Adding up each Array element.

 

What about the “Product” part of Sumproduct ?

Remember back at the start where we saw the Definition of Sumproduct,

SUMPRODUCT(array1, [array2], [array3], …)

Only Array 1 is required, Array 2, Array 3 etc are optional, that’s what the square brackets [ ] mean.

 

Multiple Arrays

Goto Sheet 2 in the Example file:

We will look at a simple example using two arrays

The data consists of Sales data.

Often we want to know what the total sales are

We do this by  adding a Sales column

Which multiplies the Qty and Price columns

And then Sum (Add) up this new column

Returning our Total Sales of 15,000

 

Now we can manually check the above as the numbers are simple eg: 100*20 = 2,000 etc

And we can sum up the Sales and see that we in fact had total sales of 15,000

 

Well this is exactly what Sumproduct is made to do:

In a Blank cell enter: =SUMPRODUCT(D4:D8,E4:E8)

Excel will return 15,000.

So what is Sumproduct doing?

Lets look inside and see what’s going on

In the Example File, Sheet2, H1 there is a copy of the data laid out as below

Note that our formula =SUMPRODUCT(D4:D8,E4:E8)

Has two Arrays

Array 1: D4:D8

Array 2: E4:E8

Note that each corresponding Array Element is multiplied together

100 x 20

20 x 200 etc

These are the products of the two Arrays

Finally the Products are Added together and the correct answer 15,000 is returned.

So Sumproduct is the Sum of the Products of the Arrays

Of course we can extend that to a large number of Arrays, columns in this case, if we wish.

 

Sumproduct with Logic

In the above two examples we saw that Sumproduct can Sum a single Array and can Sum the Product of two or more Arrays.

We can use that to our advantage and build logic into the arrays, allowing us to optionally include some array elements and leave out others.

How?

Sumproduct will always add up the product of all Arrays.

So by including an Array where the elements within the Array that we don’t want to Sum are Zero and the Elements within the array that we do want to Sum are 1 we can control what is included in the final Summation.

Goto our Example File on Sheet3

Lets say we only want to include the Sales from our Northern Region

One way to do this is to purely delete the other entries

But what if we could do that without altering our worksheet or there are thousands of rows of data?

This is where Sumproduct comes into its own.

What we need to do is add some logic to our equation, effectively doing:

Lets try it with Sumproduct

In Cell F12: type =SUMPRODUCT(D4:D8,E4:E8,{FALSE;TRUE;FALSE;FALSE;TRUE})

Excel displays a –

Excel doesn’t know what to do with the True/False and so converts them to 0

We can force excel to evaluate these as numbers by adding a simple “1*”

In F14: Type =SUMPRODUCT(D4:D8,E4:E8,1*{FALSE;TRUE;FALSE;FALSE;TRUE})

Excel now displays 5,000 the total sales from the North

To see what has happened in F16 type: 1*{FALSE;TRUE;FALSE;FALSE;TRUE}, but don’t press Enter press F9 instead.

Excel displays ={0;1;0;0;1}

The use of the 1* has converted each of the Array elements from a True/False to a 1,0 respectively.

So our 3 arrays are now:

Now adding an Array of 1*{FALSE;TRUE;FALSE;FALSE;TRUE} every time we wanted to add some numbers isn’t a practical solution.

Excel has the ability to work construct an Array on our behalf!

In E18: enter  =SUMPRODUCT(D4:D8,E4:E8,1*(C4:C8=”North”))

Excel will display 5,000

So 1*(C4:C8=”North”) is exactly equal to our previous array 1*{FALSE;TRUE;FALSE;FALSE;TRUE}

1*(C4:C8=”North”) = 1*{FALSE;TRUE;FALSE;FALSE;TRUE}

At the heart of this is that Excel is evaluating each cell in the Range: C4:C8 against our required logic =”North” and setting up an Array for us internally.

Simplify

The power of Sumproduct is therefore in that we can now simplify and extend

In cell E20 type: North

In cell F20 type: =SUMPRODUCT(D4:D8,E4:E8,1*(C4:C8=E20))

Excel will display 5,000

This simple addition allows us to vary the Summation based on the value in E20

We don’t need to multiply our logic array by 1, we can actually use any number or another Array.

In cell F22 type: =SUMPRODUCT(D4:D8,(E4:E8)*(C4:C8=E20))

This works as (C4:C8=E20) is returning an Array of True/False which get converted to an array of 1/0’s when subject to any maths.

The Math in this case is the multiplication by the 2nd Array (E4:E8)*(C4:C8=E20)

 

In Cell F24 type: =SUMPRODUCT(Qty, Price *(Region=SalesRegion))

Excel will display 5,000

But notice that by using Named Ranges/Formula how simple the logic of the equation has now become.

 

Rahul’s Question (Multiple Criteria):

In Comment No. 55: Rahul asked, “Can you give an example work sheet of above example

Sheet 4 in the Example File is the answer.

In Cell C23: type: =SUMPRODUCT(- -(A2:A21=”Luke Skywalker”),- -(B2:B21=”West”),C2:C21)

Excel will display 141, which is the sum of the Sales made by Luke Skywalker in the West Region.

However using what was learned above, this is better simplified to:

C26: =SUMPRODUCT((Name=SalesMan)*(Region=SalesRegion)*Sales)


The Double Unary

In the formula above Chandoo has used what is known as a Double Unary, which is 2 – signs next to each other (I have inserted a space above to make it more legible).

Two – signs are the same as saying

– -(A2:A21=”Luke Skywalker”) = -1 x -1 x (A2:A21=”Luke Skywalker”)

-1 x -1 is 1

Technically this is the most efficient way for Excel to perform any maths on the Array

– -(A2:A21=”Luke Skywalker”)

So that the Array of true/Falses made by (A2:A21=”Luke Skywalker”) is converted to an Array of 1/0’s for use in Sumproduct.

At the slight expense of speed but for improved readability and understandability by others I prefer the use of 1* instead of – – and you will mostly see that convention in my posts.

Chandoo:            – –(A2:A21=”Luke Skywalker”)

Hui:                       1*(A2:A21=”Luke Skywalker”)

In fact any maths performed on the array will convert its contents to an array of 1/0’s, so long as the maths doesn’t change the Arrays values

For a real good discussion on this topic have a look at the post The Venerable SUMPRODUCT at ExcelHero.com

 

Other Links to Sumproduct

http://chandoo.org/wp/2009/11/10/excel-sumproduct-formula/

http://chandoo.org/wp/2011/05/26/advanced-sumproduct-queries/

http://chandoo.org/wp/tag/sumproduct/

http://www.excelhero.com/blog/2010/01/the-venerable-sumproduct.html

 

DOWNLOAD

You can download a copy of the above file and follow along, Download Here.

 

OTHER POSTS IN THIS SERIES

You can learn more about how to pull Excel Formulas apart and what makes them tick in the following post:

Formula Forensic Series:

 

FORMULA FORENSICS NEEDS YOUR HELP !

I am running out of ideas for Formula Forensics and so I need your help.

If you have a neat formula that you would like to share and explain, try putting pen to paper and draft up a Post as Luke did in Formula Forensics 003. or like above.

If you have a formula that you would like explained but don’t want to write a post also send it in to Chandoo or Hui.

 

XMAS BREAK

This will be the last Formula Forensics Post for 2011, but rest assured that we will be returning in early 2012.

I’d like to take the opportunity to thank Chandoo for allowing me the space and freedom to post pretty much what ever I’ve wanted at Chandoo.org. I hope you have enjoyed my contributions to the Chandoo.org community over the past year.

On behalf of Eva and myself I’d like to wish you all a very Merry Xmas and a Happy and Safe New Year ahead

Hui…

Merry Xmas

 

Facebook
Twitter
LinkedIn

Share this tip with your colleagues

Excel and Power BI tips - Chandoo.org Newsletter

Get FREE Excel + Power BI Tips

Simple, fun and useful emails, once per week.

Learn & be awesome.

Welcome to Chandoo.org

Thank you so much for visiting. My aim is to make you awesome in Excel & Power BI. I do this by sharing videos, tips, examples and downloads on this website. There are more than 1,000 pages with all things Excel, Power BI, Dashboards & VBA here. Go ahead and spend few minutes to be AWESOME.

Read my storyFREE Excel tips book

Overall I learned a lot and I thought you did a great job of explaining how to do things. This will definitely elevate my reporting in the future.
Rebekah S
Reporting Analyst
Excel formula list - 100+ examples and howto guide for you

From simple to complex, there is a formula for every occasion. Check out the list now.

Calendars, invoices, trackers and much more. All free, fun and fantastic.

Advanced Pivot Table tricks

Power Query, Data model, DAX, Filters, Slicers, Conditional formats and beautiful charts. It's all here.

Still on fence about Power BI? In this getting started guide, learn what is Power BI, how to get it and how to create your first report from scratch.

38 Responses to “Time to showoff your VBA skills – Help me fix ActiveSheet.Pictures.Insert snafu”

  1. shokks says:

    I tried your code with 2003, it works.

    But, I know Addpicture does not take URLs anymore with 2007 onwards, perhaps its the same with picture.insert as well.

    http://support.microsoft.com/kb/928983/en-us

    The above link gives the solution as "picture fill in a shape such as a rectangle".

  2. Vince E. says:

    Tried to recreate this, but it worked fine for me. I just took the image of the error you showed in the post. Is there more info that can narrow this down a bit?

  3. Ian Hinckley says:

    Hi

    Not sure if this is what you're after, but I just tried this

    Sub Macro1()
    ActiveSheet.Pictures.Insert("http://www.google.co.uk/intl/en_uk/images/logo.gif").Select
    End Sub

    Tied a button to it on the sheet and it seems to work; hope this helps a little

    Ian

  4. Chandoo says:

    @All.. the issue is in Excel 2007. In 2003 ActiveSheet.Pictures.Insert seems to work fine. Unfortunately, I have design this in Excel 2007.. that is why I posted it here..

  5. Ian Hinckley says:

    v2

    Sub Macro1()
    Set n = ActiveSheet.Pictures.Insert("http://www.google.co.uk/intl/en_uk/images/logo.gif")
    With Range("c12")
    t = .Top
    l = .Left
    End With
    With n
    .Top = t
    .Left = l
    End With
    End Sub

    Ian

  6. Ian Hinckley says:

    That didn't come out very well. This positions at c12, so can change easily:
    Sub Macro1()
    Set n = ActiveSheet.Pictures.Insert("http://www.google.co.uk/intl/en_uk/images/logo.gif")
    With Range("c12")
    t = .Top
    l = .Left
    End With
    With n
    .Top = t
    .Left = l
    End With
    End Sub

    Works OK in 2007

    Ian

  7. Chandoo:
    Try 'ActiveSheet.Pictures.Insert'

    With ActiveSheet.Pictures.Insert("C:\Example.png")
    .Left = ActiveSheet.Range("A1").Left
    .Top = ActiveSheet.Range("A1").Top
    End With

  8. Jon Peltier says:

    activesheet.pictures.insert "C:\Documents and Settings\Jon Peltier\Desktop\2007 stuff\insert_charts_2007.png"

    Works for me in 2003 SP3 and in 2007 SP2.

    Check the URL, and make sure you have internet connectivity.

    What also works, and is newer (pictures.insert was supposedly deprecated in '97):

    activesheet.shapes.addpicture "C:\Documents and Settings\Jon Peltier\Desktop\2007 stuff\insert_charts_2007.png", false, true, 200,200,100,100

    Unfortunately you must specify dimensions (the last four arguments) and you don't necessarily know them. But the picture size is still related back to the original picture size, so you could use scaleheight and scalewidth to fix this.

  9. Chandoo: I just re-read your post.

    The code I posted works for me. However, I'm using a local picture. If you try to add a picture from the web, this won't work.

    I remember solving this problem before by adding a rectangle shape first, then using the Shapes.AddPicture method to get a picture from the web.

    I'll find that code and post it here.

  10. Chandoo says:

    Some more updates... The code "ActiveSheet.Pictures.Insert (path)" works fine in Excel 2007 at home. Strange it failed miserably on my work laptop. Do you think this has got something to do with SP2 of MS Office 2007 or something like that?

    @Ian, Jon: Thanks for the code snippets. I guess I will use my home installation of excel to do this.

  11. Chandoo:

    Try this on your work laptop:

    Sub test()
    ActiveSheet.Shapes.AddShape msoShapeRectangle, 50, 50, 100, 200
    ActiveSheet.Shapes(1).Fill.UserPicture _
    "http://www.datapigtechnologies.com/images/dpwithPig6.png"
    End Sub

  12. Jon Peltier says:

    I didn't mean to post code with a local file, because both approaches worked with an internet image as well. This is in Excel 2007 SP2.

    activesheet.pictures.insert "http://peltiertech.com/images/2009-07/col_area_noblanks.png"

  13. Jon: Looks like I have SP1 on my client machine! I wasn't paying attention.

    Just checked my home computer where I have SP2, and you're right...looks like they fixed it.

  14. Jon Peltier says:

    I didn't even bother testing in SP1, though I could if anyone cares enough.

  15. teylyn says:

    I'm afraid I don't have a solution, but I find it remarkable that after attaining a certain status in the Excel world, Chandoo does not need to post on an Excel discussion forum to get help for an Excel problem. Instead, he posts on his blog and all the gurus come rushing to his help.

    Isn't Web 2.0 great?

  16. Jon Peltier says:

    Teylyn - I saw Chandoo's tweet first, and followed the link back to his blog.

  17. Chandoo says:

    @Mike.. thank you. I have seen the fill rectangle solution before posting the query here. For that matter, I have also tried the solution of embedding a browser control on a spreadsheet. both of these seemed a bit extreme. That is why I have asked it here.

    But I guess I will end up using it if I had to build this in work laptop.

    @Teylyn: I have thought of posting this in a forum. (Unfortunately I have not been to any excel group in the last 5 years. Last time I was active was when I built a jave based excel sheet construction solution using POI.HSSF classes of Apache... ) After searching for a few hours, I found several forum posts where others had same problem and the solution recommended (using .left and .top parameters) is not working for me. Incidentally most of these solutions are from a certain Jon Peltier 😛

    I thought may be the problem is interesting for fellow blog readers. So I posted it here.

  18. Justin B says:

    Hi,
    Adapting the code in the question,

    [code]
    Sub InsPicture()
    pPath = "http://chandoo.org/images/pointy-haired-dilbert-excel-charts-tips.png"
    With ActiveSheet.Pictures.Insert(pPath)
    .Left = Range("a1").Left
    .Top = Range("a1").Top
    End With
    End Sub
    [/code]

    Seems to work fine

  19. Jon Peltier says:

    Looks like it was a problem in 2007 up to SP1, which was corrected in SP2.

  20. Chandoo says:

    @Jon.. seems like the case. I just checked the version at work laptop. it is 12.0.6331.5000 (SP1).

    Thank you so much every one. I really appreciate your time and suggestions in solving this.

  21. Jon Peltier says:

    Glad to help. I couldn't understand why something so straightforward wasn't working.

  22. Kieranz says:

    Hi All
    Is there a way of inserting a motion clip eg animated gif or swf or flv?
    Thks

    • Chandoo says:

      You can insert animated GIFs by inserting them in a browser control through VBA. For other types of movies, I can guess you can insert them as clip art.

  23. ashvini says:

    I WANT THE INSERT PICTURE BY USING COADING

  24. Lutz says:

    so currently i was struggling same as you, chandoo, with the insert picture method in excel 2007/10 from an url and came along your thread here.

    so i re-designed the code on the addshape method as mike was suggesting it and all of the sudden it works just fine.

    thanks alot to you guys, you were a great help
    a big salut from switzerland

  25. Santiago says:

    Hi guys,

    I need help copying and pasting an image with the path in a cell.
    I leave the code.

    And thank you very much!

    Sub Copiarimg()

    Dim pic As Picture

    With ActiveSheet

    Set pic = .Pictures.Insert(Range("f2").Value)

    With .Range("e9:g22")
    pic.Top = .Top
    pic.Left = .Left
    pic.Width = .Width
    pic.Height = .Height
    End With
    End Sub

  26. I've played around with the approaches in these comments, and the code below is what I've come up with. The ImagePath can be a local file or a URL. As Jon mentioned above, the trick is to set an arbitrary value for the width and height, then call the ScaleWidth and ScaleHeight methods afterward to reset the picture to its original size. Once the LockAspectRatio property is set, you can change the picture width and the height will automatically scale (or vice-versa).

    Sub AddPictureToRange(TopLeftCellAddress As String, ImagePath As String)

    Dim pic As Shape
    Dim l As Single, t As Single
    Dim temp As Single

    l = Me.Range(TopLeftCellAddress).Left
    t = Me.Range(TopLeftCellAddress).Top
    temp = 10# ' arbitrary value

    Set pic = Me.Shapes.AddPicture(ImagePath, msoFalse, msoTrue, l, t, temp, temp)
    pic.ScaleHeight 1#, msoTrue
    pic.ScaleWidth 1#, msoTrue
    pic.LockAspectRatio = msoTrue

    End Sub

  27. dip says:

    I need some help with inserting pictures. I have an excel file with a column of item numbers next to this row I want to insert a picture of this item. The pictures are coded with the item number so I tried to insert it with one of the codes above:

    Sub InsPicture()
    pPath = "http://img.bricklink.com/P/80/55236.gif"
    With ActiveSheet.Pictures.Insert(pPath)
    End With
    End Sub

    That worked but I need to do that for every row separtly.
    So I tried in the code
    pPath = "http://img.bricklink.com/P/80/"&Text(a1;"#")&".gif"

    But that gives errors.

    Anybody ideas?

  28. alex says:

    Hi Nicholas, I used your solution in a related problem in Excel 2003 and it worked flawlessly..thank you!

  29. Richard says:

    Hi Mike Alexander,

    Your solution with some changes was helpful in my problem in XL 2007, thanks.

  30. seejay says:

    Hi,

    thanks all. In addition, I had a problem with multiple pictures inserting (every new picture replaced the prior one). I've changed it a bit, may be helpful..

    Sub test()
    ActiveSheet.Shapes.AddShape msoShapeRectangle, 50 , 50, 100, 200
    ActiveSheet.Shapes(1).Fill.UserPicture _
    "http://www.datapigtechnologies.com/images/dpwithPig6.png"
    ActiveSheet.Shapes(1).Copy
    ActiveSheet.Paste
    End Sub

  31. Jon Peltier says:

    Try this instead:
     
    Sub test()
    ActiveSheet.Shapes.AddShape msoShapeRectangle, 50 , 50, 100, 200
    ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture _
    "http://www.datapigtechnologies.com/images/dpwithPig6.png"
    End Sub

    • Kez says:

      Thanks to everyone, this thread has been very helpful. However, image inserting still doesn't work quite as expect for me.

      While I can get a picture inserted into an Excel 2010 worksheet using either:

      1) ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture...
      2) ActiveSheet.Pictures.Insert(pPath), and
      3) Shapes.AddPicture...

      unfortunately the images all insert with a display size determined not by the actual pixel dimensions of the image but by the dpi resolution.

      So for example, if I insert two copies of the exact same 600x600 pixel image, one with a 300dpi resolution and the other with 72dpi, they display at vastly different sizes on screen.

      While this might be intended behaviour for Excel in order to maintain a WSYWIG printing layout, I actually need a way to insert the image based on the the actual pixel dimesnsions and ignoring the dpi resolution.

      Any help appreciated.

      Thanks
      Kez

  32. Kez says:

    Not doing an intentional bump, but realised I posted in rely to one of the repsonses here instead of to the main thread, so reposting.
    =====

    Thanks to everyone, this thread has been very helpful. However, image inserting still doesn’t work quite as expected for me.

    While I can get a picture inserted into an Excel 2010 worksheet using any of the below methods:

    1) ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture....
    2) ActiveSheet.Pictures.Insert(pPath), and
    3) Shapes.AddPicture....

    unfortunately the images all insert with a display size determined not by the actual pixel dimensions of the image but by the dpi resolution.

    So for example, if I insert two copies of the exact same 600×600 pixel image, one with a 300dpi resolution and the other with 72dpi, they display at vastly different sizes in Excel on screen.

    While this might be intended behaviour for Excel in order to maintain a WYSIWYG printing layout, I actually need a way to insert the images based on the the actual pixel dimesnsions and ignoring the dpi resolution.

    Any help appreciated.

    Thanks
    Kez

  33. Kez says:

    Well, answered my own question 🙂

    For those who might be interested, you can use this function:

    Public Function GetPicDims(strFilePath As String, strFileName As String) As String
    GetPicDims = CreateObject("Shell.Application").Namespace((strFilePath)). _
    ParseName(strFileName).ExtendedProperty("Dimensions")
    End Function

    to get the dimensions of the image you want to insert. Then you can parse the return string and use the width and height values to add a rectangle shape of the appropraite size, like:

    ActiveSheet.Shapes.AddShape msoShapeRectangle 50, 50, iWidth, iHeight

    which you then fill with the picture:

    ActiveSheet.Shapes(ActiveSheet.Shapes.Count).Fill.UserPicture "c:\temp\test.jpg"

    This way the picture gets inserted using the pixel dimensions and the (print) resolution gets ignored.

    If desired, the GetPicDims function can be made more generic to get other ExtendedProperties.

    Regards
    Kez

Leave a Reply