(my finished Excel file)

Using only conditional formatting and formulas make this face move around an Excel sheet and interact with cells containing numbers.

(my previous post used vba to move around)

**Default Eye Position**

- left eye: row 9 (cell N103), column 6 (cell P103)
- right eye: row 9 (cell N104), column 11 (cell P104)

**Adjusting Default Eye Position**

Clicking the arrow buttons assigns numbers to cells F102 and J102. Formulas in the green area adjust the starting point values based on the arrow button values.

**Make the Eyes Move!**

These conditional formatting rules are the final step to make the eyes move!

- =AND(ROW(A1)=$S$103,COLUMN(A1)=$W$103)
- =AND(ROW(A1)=$S$104,COLUMN(A1)=$W$104)

Change blue eye color to brown or green if you wish.

**Excel File Moving Eyes**

Click the arrows to see the eyes move! See how it works in this Excel file.

Repeating the same steps we add Mouth, Hair, Sideburn left, Sideburn right, Nose and Face.

Now we can move the completed face using the arrows keys.

Challenge: **trigger an action based on the face touching any cell with a number.**

Concept: I ended up using formula based intersection method. Not easy but it worked!

**Face Named Range**

Here’s the dynamic named range for the moving face:

=OFFSET(Sheet1!$A$1,Sheet1!$AC$115-1,Sheet1!$AG$115-1,Sheet1!$S$115,Sheet1!$V$115)

**List All Cells With Numbers**

If I simply hard coded cell references to match cells with numbers then this works:

=SUM(I17 face)

This uses intersect method to determine if cell I17 and named range face intersect. As cell I17 would have a number in it I can further test if this intersection is >0.

But isn’t that lame? I want to allow you to add/remove cells with numbers.

Solution: I used a multi column approach to solve this in rows 126 to 141. You can enter numbers in 15 different cells. The message box lets you know whether or not the face intersects a cell with a number.

It works! The face interacts with cells that contain a number. The message box is basic but it proves that it’s possible!

This is not very practical but it was a fun challenge and great practice!

99% of Excel users have no idea how powerful Excel is. Curiosity and determination enable creative solutions in Excel.

You could possibly create a quiz in Excel using this method. Cells could be different categories and intersecting a cell could display a random question from that category.

Of course I kept playing around with this. Now the message box also displays the number from the intersecting cell.

Earlier I mentioned curiousity and determination. I forgot to mention that I broke one of my golden rules: no coffee after 4 pm!

I’m a Data Analyst and Excel enthusiast.

I live in Markham Ontario Canada (near Toronto).

Outside of Excel I enjoy hanging out with my dogs Cali and Fenton.

]]>(Excel file found below using VBA. Read instructions carefully before using)

The Space Invader logo was my inspiration for this mini game. Memories of early 1980s computer games passed through my mind while I waited for my burger to cook.

I came up with the idea of making a character move around the screen to capture the beer logos.

“

How would the character move?“

This is our hero who needs to collect beer in order to celebrate Spreadsheet Day with his friends!

He needs to collect beer in a timely manner while avoiding nasty beer!

I had never used the VBA OnKey syntax. I figured this was a great time to use it! OnKey changes the behavior of the keyboard. I used it to assign macros to the arrow keys.

Sub TurnOnArrows()

Application.OnKey “{RIGHT}”, “MoveR”

Application.OnKey “{LEFT}”, “MoveL”

Application.OnKey “{Down}”, “MoveD”

Application.OnKey “{UP}”, “MoveU”

End Sub

I attached a simple action to “MoveR” and the others to ensure that it was working.

NOTE: in the file I have carefully documented how to return to the keyboard’s default behavior (so arrows won’t run the macros). There are two automatic ways and also a manual button.

This is the code that restores the default arrow behavior:

Sub TurnOnArrows()

Application.OnKey “{RIGHT}”

Application.OnKey “{LEFT}”

Application.OnKey “{Down}”

Application.OnKey “{UP}”

End Sub

After experimenting I settled on combining Selection.Cut with ActiveCell.Offset(0, rightvalue).Activate and Selection.Paste to make him move around the screen.

rightvalue is a variable but it made the most sense to move him 8 squares each time an arrow key was pressed (character is 8X8).

So finally….I was able to press the arrows and move him! Cool!

I had a vague memory of the VBA intersect method. It took a LONG time to get the code just right.

For each arrow click I had to check if the character intersected with the placement of the four beers.

Set me_beer = Application.Intersect(Range(“

me”), Range(“grid!$AZ$14:$BH$27, grid!$BX$32:$CD$43,grid!$W$46: $AE$59,grid!$AW$51:$BC$62″))

This checks if named range me intersects with any beer in sheet grid. Beautiful

If there’s no intersection then simply move him in the direction of the clicked arrow key.

If there is intersection (meaning he grabs a beer) then increase the beer score! Yes, I created a way to track the beers collected and subtract points for touching nasty bad beer (don’t buy cheap beer for your friends on Spreadsheet Day!). Check out sheet ‘stats’. A perfect score is 36.

Check out sheet ‘stats’. A perfect score is 36. How fast can you collect your beer and share it with your friends? Can you get 36 points in less than 30 seconds?

My exciting Excel Beer Game v3.0 should entertain you for 1 or 2 minutes. Please save and close all other Excel files before opening my Excel file.

Yes it’s a bit lame but the point is to make learning fun! Now I know how to use intersect and onkey!

Maybe I could make the Space Invaders move around a bit. It would be harder to capture them! Or what about customizing the character’s features? That seems possible but I ran out of time. Maybe for the next version!

Here are some beer companies from Ontario Canada. Great variety and taste:

- https://www.refinedfool.com/
- https://www.rougeriverbrewingcompany.com/
- https://www.amsterdambeer.com/

I’m not getting paid to say that their beer is great but if you want to send me some free swag or beer that would be fantastic!

I remember the classic games from the early 1980s. Sometimes we would change the code for games on the TRS80.

In 7th grade we were given computer time on the Vic20. I had this funny idea to change some code and output a message about our principal Mr. Durfy. Fortunately I didn’t use any bad words because just as I ran the code I realized that he was right behind me looking over my shoulder. Man….I was so lucky that he found it amusing!

]]>

Numbers describe height, intelligence and tests. How do we compare these numbers to others?

- Tim is 2 meters tall! That’s extremely tall!
- Sonja’s IQ is 117. She’s a genius!
- I got 76% on the test. Not bad.

We’ll use height. Normal Distribution & Standard Deviation allow us to compare height.

It’s easier to visualize than test scores or IQ. In a crowd you compare the height of those around you. Internally you do the math.

Bill Jelen (Mr Excel) and I in 2015.

Bill is 6 feet 1 inch (185 cm). I am 6 feet 4 inches (194 cm).

Instead of using adjectives to describe our height we’ll use standard deviations.

**What do height, I.Q. and test scores have in common?** All are normally distributed.

Chart below shows: most are close to the mean(average), half are above the mean and half are below.

Some are taller (to the right) or shorter (to the left). Very few are extremely tall or short.

In the U.S. average male height is 5 feet 9.3 inches (69.3 inches, 176 cm). source

Left and right sides of the chart are symmetric. Normally distributed data-sets share this symmetry but the spread varies. Values may cluster around the mean or be more spread out. Standard deviation measures this. Normal distribution is also known as Gaussian distribution and the bell curve.

Measures the spread of the numbers from the average (mean) in normally distributed data-sets.

- 68.27% of values are within one standard deviation of the mean.Â
- 95.45% of values are within two standard deviation of the mean.Â
- 99.73% of values are within three standard deviation of the mean.Â

It works for all normally distributed data-sets. In statistics this is known as the empirical rule.

Data clusters closer to the mean as standard deviation decreases. The empirical rule still works.

For U.S. male height 1 standard deviation = 2.94 inches (7.5 cm). Let’s explore this in Excel!

In sheet ‘INPUTS & DATA’ I created a sample date-set using:

- mean male height of 5 feet 9.3 inches (69.3 inches, 176 cm)
- standard deviation of 2.94 inches (7.5 cm)
- formula in column E =NORM.INV(RAND(), 69.3, 2.94)Â (pasted as values)

Below we see the sample of 30000 produced results very close to the empirical rule.Â

- 20510 (68.37%) within 1 stand dev of mean (66.37 to 72.24 inches, 68.57 to 183.49 cm)
- 28618 (95.39%) within 2 stand dev of mean (63.43 to 75.18 inches, 61.11 to 190.95 cm)
- 29932 (99.77%) within 3 stand dev of mean (60.49 to 78.11 inches, 53.65 to 198.41 cm)

Displayed using feet and inches:

- 68.37% are between 5 feet 6 inches and 6 feet 0 inches.
- 95.39% are between 5 feet 3.4 inches and 6 feet 3.2 inches.
- 99.77% are between 5 feet 0 inches and 6 feet 6 inches.

Bill’s 1.26 standard deviation is between the 1st & 2nd deviation above the mean.Â

My 2.38 standard deviation is between the 2nd & 3rd deviation above the mean.Â

Men above 6 feet 6 inches (past 3rd standard deviation) are extremely tall. Kevin Durant is 6 feet 11 inches with a standard deviation of 4.7

This entire post I’ve been referring to male height in the United States.

**What if Bill and I were to travel to Bolivia? Would we be taller?**Â

Of course not but we’d be perceived as being taller by the local people! In Bolivia my height would put me 4.5 standard deviations above the 5 feet 3 inch mean (2.92 inch SD). Bill would be 3.4 standard deviations above the mean.Â If we traveled to The Netherlands my standard deviation would be 1.7 and Bill’s would be 0.6. We would blend in quietly. Isn’t that weird?

If a data-set is perfectly symmetrical (left side of chart is exactly like right side) the skew is zero.

Our sample of 30000 gave us a skew of 0.00561Â Closer to zero means more symmetrical.

In sheet ‘STATS’ row 26 I calculate the skew for various small samples.

- skew = -0.6108 (10 rows of sample data)
- skew = -0.1818 (100 rows of sample data)
- skew = -0.0972 (1000 rows of sample data)
- skew =Â 0.0072 (10000 rows of sample data)

The skew decreases as we include more data! If a data-set is truly normally distributed the skew approaches zero as the sample increases.

In sheet ‘STATS’ rows 23 & 24 we see the mean and median values for the small samples. Row 25 shows that the absolute difference decreases as we include more sample data!

The mean and median values get closer and closer as we increase the sample size.

- 0.832 absolute difference (10 rows of sample data)
- 0.169 absolute difference (100 rows of sample data)
- 0.041Â absolute difference (1000 rows of sample data)
- 0.026Â absolute difference (10000 rows of sample data)

Horizontal axis labels are linked to cells I14:I22 (sheet STANDARD DEVIATION CHART).

To get the right look and functionality I used three chart tricks.

(1) They weren’t displaying properly (text was jammed together)

To fix this I forced two carriage returns using the CHAR function. Character 10 does the magic. Now the text displays nicely in three lines.

(2) I wanted a way to easily switch between metric and imperial

I added a check box (check = metric, uncheck = imperial) and used the TRUE FALSE in the formula.

(3) I only wanted to display the integer (not all the decimals)

I used the TEXT function to format the number. I also could have used the FLOOR function.

The end formula is a bit long but it gets the job done:

=IF(H13=0,””,IF(H13=1,”man “,”men “)&CHAR(10)&IF($J$12,TEXT(F12,0)&” to “&TEXT(F13,0)&CHAR(10)&” inches”,TEXT(G12,0)&” to “&TEXT(G13,0)&CHAR(10)&” cm”))

Download my Excel file. There are 5 sheets:

- INPUTS & DATA enter parameters to create data-set
- PIVOT TABLE & CHART summarize & visualize
- STANDARD DEVIATION CHART visualize by standard deviations
- STATS additional statistics
- HEIGHT EXAMPLES used in this post

To see how to create the sample data you can replace the pasted values in column E sheet INPUTS & DATA)Â with formula =NORM.INV(RAND(), $B$5, $B$8)

There’s so much more to learn! Here are some interesting www links:

- Investopedia’s Normal Distribution explanation.
- Interesting articles and calculators at Tall.Life.com
- KhanAcademy NormalDistributionIntroÂ and Excel file.
- How tall is tall discussion at Quora.
- Advanced statistics from statisticsbyjimÂ

My name is Kevin Lehrbass. I’m a Data Analyst.

Normal stores rarely sell my pant size. L.L. Bean’s catalog used to have my size but not any more.Â Big & Tall stores say “we don’t have that small size” or they do but a single pair costs a fortune.

Fortunately that day I did find my size and there was a sale! I bought all the pairs they had in stock!

]]>

A UDF is a special kind of VBA. It allows you to create functions! Let’s start with an example.

HereÂ we shared formula solutions to Leila’s challenge: *look for the App in range B5:D45, get column header B4:D4.Â *See how Geraldo’s GetDiv UDF solves this!

Geraldo shared this UDF solution:Â (Download zipped Excel file)

Function GetDiv(LookupVal As String, Titles As Range, SearchArea As Range) As String

GetDiv = Cells(Titles.Row, SearchArea.Find(LookupVal).Column)

End Function

Geraldo’s function used in cell L5:

=GetDiv(H5,$B$4:$D$4,$B$5:$D$45)

His explanation helped me understand:

The function expects 3 parameters GetDiv (

LookupVal,Titles,SearchArea) as below:

1stLookupValÂ is the value we are looking for ($H5 for the first App name)

2ndTitlesis the range where we have the Divisionsâ€™ names: $B$4:$D$4

3rdSearchAreais the area where we’ll look for theLookupVal: $B$5:$D$45

Initially I thought SearchArea was a vba property(it’s a name for where we look for the App).

Now let’s explore further by playing with the code!

This part SearchArea.Find(LookupVal).Column seemed odd so in sheet ‘test Geraldo’s udf‘ I started playing with some vba.

**How does Range.Cells property work?** (SearchArea is a range parameter)

In a basic form it needs two numbers: one for a row, one for a column.

This code assigns a text value to cell E3:

‘provide simple co-ordinates to Cells

Sub Assign_Text_To_A_Cell()

Cells(3, 5).Value = “assign text to a single cell”

End Sub

Cell E3 (row 3, column 5) now has text “assign text to a single cell”.

We could also extract the existing value from a cell:

‘extract the value from a cell and display it in a message box

Sub Extract_and_Display_value()

Dim getvalue As String

getvalue = Cells(9, 3).Value

MsgBox (getvalue)

End Sub

There are many possible applications of Range.Cells! Let’s go back to Geraldo’s code:

Cells(Titles.Row, SearchArea.Find(LookupVal).Column)

Titles.Row is range B4:D4. SearchArea.Find(LookupVal).Column provides a column number so we know which text from B4:D4 to retrieve.

Another way to explainÂ SearchArea.Find(LookupVal).Column is:

In range G16:I18 what is the column number where we find the word “fish”?

This code displays the column number where “fish” is found:

‘Letâ€™s examine syntax: SearchArea.Find(LookupVal).Column from UDF GetDiv

Sub examinesyntax()

Dim LookupVal As String, SearchArea As Range, GetColumnNumber As Integer

LookupVal = â€śfishâ€ť

‘SearchArea = Range(â€śG16:I18â€ť) <â€“wrong syntax. Google search helped to create next line

Set SearchArea = Sheets(â€śtest Geraldoâ€™s udfâ€ť).Range(â€śG16:I18â€ť)

GetColumnNumber = SearchArea.Find(LookupVal).Column

‘Had to google for help with MsgBox syntax

MsgBox (â€śWhat is the column number where we find the word fish?â€ť & vbCrLf & â€śItâ€™s column â€ť & GetColumnNumber & â€ś.â€ť)

End Sub

Building the code really helped me understand SearchArea.Find(LookupVal).Column.

Ready for more vba fun?!

Let’s see how the code behind the right button works (show column number for random item) !

In this case the random word is “orange”.

Rerun to see different random word.

Here’s the code behind the message box:

‘Add more functionality: select random word, show col number

Sub examinesyntaxv2()

Dim LookupVal As String, SearchArea As Range, GetColumnNumber As Integer, Randr As Integer, Randc As Integer, Lookupword As String

Randr = WorksheetFunction.RandBetween(16, 18) ‘random row

Randc = WorksheetFunction.RandBetween(7, 9)Â Â Â ‘random column

Lookupword = Cells(Randr, Randc).Value

‘SearchArea = Range(“G16:I18”) <–wrong syntax. Google search helped to create next line

Set SearchArea = Sheets(“test Geraldo’s udf”).Range(“G16:I18”)

GetColumnNumber = SearchArea.Find(Lookupword).Column

‘Had to google for help with MsgBox syntax

MsgBox (“What is the column number where we find the word ” & Lookupword & “?” & vbCrLf & “It’s column ” & GetColumnNumber & “.”)

End Sub

Now you won’t always get “fish” Notice that vbCrLf creates a carriage return in the MsgBox.

The knowledge doesn’t fall from the sky. I have to practice! Necessity and curiosity (and caffeine) fuel my learning but there’s a lot of tinkering, many google searches for syntax ideas and some grit to get the code just right

By the way…who is Geraldo??? Who is the person behind the GetDiv UDF?

Geraldo is a Data Analyst from SĂŁo Paulo Brazil.

He loves challenges and creating solutions to solve them!

Geraldo has worked in Finance and knows his way around Excel (pivots, formulas, vba), SQL, Cobol, DBase III, VBS, ASP/XML and now the new stuff: Power BI (M, Dax) with Python being his next thing to conquer! An amazing set of skills!

Thanks for the UDF Geraldo and I look forward to learning more from you!

Learn, build stuff, repeat. That’s it! You can learn a lot of vba on your own but there are many tips and nuances that you can learn from a professional. More structured learning often helps get past certain hurdles.

How you learn is up to you (books, videos, etc). Here are some suggestions:

- Paul Kelley’s website
- Leila Gharani’s YouTube channel
- Jon Acampora’s How to write a UDF
- Dan Strong’s YouTube channel
- Dinesh Kumar Takyar’s YouTube channel
- Sumit Bansal’s Guide to creating a UDF

My name is Kevin Lehrbass. I’m a Data Analyst living in Markham Ontario Canada.

I often spend hours playing with Microsoft Excel but eventually a few things happen:

- My dogs get mad at me (they want to play)
- I need more coffee
- There’s a strange pain in my stomach. Oh yeah…food.

I have two wonderful dogs Cali and Fenton. Here you see Cali demanding that I take a break from the spreadsheet. We’ll go play in the backyard for awhile and then read a book (Excel or Power BI) on the couch

]]>

1)**Kevin’s FEN viewer basic**,Â 2)**Kevins-FEN-viewer-plus-v3**Â (database, FEN explanation).

Given this FEN text…

r6k/2R5/6R1/pp1Ppp2/8/Pn2B1Pr/4KP2/8 w – – 0 1

…we can create this chess position:

A FEN is split into 8 parts separated by “/”. Each part is a row on a chess board.

**“r6k” **describes row 8 at the top. Let’s examine each item:

- lowercase “
**r**” = black rook (top left a8), - number “
**6**” = 6 consecutive blanks squares - lowercase “
**k**” = black King (top right h8)

**“****2R5****”Â **describes row 7.

- number “
**2**” = blank squares (a7 & b7) - uppercase “
**R**” = white rook - number “
**5**” = 5 blank spaces

Near the end the “**w**” indicates that it’s white’s move.

Here we see each row’s FEN code:

Robert Gascon’s ‘**Excel Chess Games Viewer**‘ inspired me to create this FEN viewer two weeks ago. I used 6 steps spread across 42 columns.

Unhide columns to see the formulas:

- on the ribbon select View and check Headings
- select columns N to BI
- right click & unhide

Steps start in column P and move to the right:

Step 1 splits FEN r6k/2R5/6R1/pp1Ppp2/8/Pn2B1Pr/4KP2/8 out per row in column P

Note: each number = consecutive blank squares. Step 6 has 8 cells representing each square in a chess row. ** A FEN is compact. My idea? Spread the FEN over 8 squares of a chess row**.

“r6k” becomes “r666666k”. “2R5″ becomes “22R55555”Â (step 6 in column AX). Audit formulas in all steps to understand fully.

On the chess board look at cell C7 array formula:

=IFERROR(INDEX($BH$7:$BH$19,MATCH(TRUE,EXACT(AX7,$BG$7:$BG$19),0)),””)

Cell C7 looks for AX7 value “r” in column BG. The answer is a chess icon from column BH.

A couple of important parts of the formula:

- “r” is different from “R” so I used MATCH(TRUE,EXACT(
- I used IFERROR (Numbers are blank squares. There’s nothing to display.)

A good summary from Wikipedia:

FEN is based on a system developed byÂ ScottishÂ newspaper journalistÂ David Forsyth. Forsyth’s system became popular in the 19th century; Steven J. Edwards extended it to support use by computers. FEN is an integral part of theÂ Portable Game NotationÂ for chess games, since FEN is used to define initial positions other than the standard one. FEN does not provide sufficient information to decide whether aÂ drawÂ byÂ threefold repetitionÂ may be legally claimed or aÂ draw offerÂ may be accepted; for that, a different format such asÂ Extended Position DescriptionÂ is needed.

- Excel formula calculates value ofÂ Chess pieces
- Robert Gascon’s Chess game viewer
- Diarmuid Early’s Chess game viewer
- Daniel Ferry’s Chess game viewer
- Pedro Wave’s Chess board PGN viewer

- Amazing Videos from Agadmator YouTube Chess Channel
- Play and learn chess: www.chess.com
- Study chess tactics (online or via book)
- Chess phone apps (i.e. ‘Chess Time’, ‘Shredder Chess’, ‘Chess Tactics Pro’)

FEN examples fromÂ ‘Kevin’s FEN viewer plus v3’:

- Row 16 agadmator: find the next move (Carlsen vs Anand)

Agadmator sometimes asks us to pause the video and find the best next move.

Subscribe to his YouTube channel! You will learn a lot.

- Row 17 my game: find the mate combo! (black’s move)

Use my Excel file to collect your FENs.

My name is Kevin Lehrbass. I’m a Data Analyst. I live in Markham Ontario Canada.

I know….two chess related Excel posts in a week is a bit too much for most. But some of us love both so why not?

]]>

Canada uses humidex calculation while the U.S. uses HeatIndex.

HumidexÂ (short forÂhumidity index) is an index number used by Canadian meteorologistsÂ to describe how hot the weather feels to the average person, by combining the effect of heat andÂ humidity

The

heat indexÂ (HI) orÂhumitureis an index that combines air temperature andÂ relative humidity, in shaded areas, to posit a human-perceived equivalent temperature, as how hot it would feel if theÂ humidityÂ were some other value in the shade.

I found what appears to be the common formulas for Humidex & HeatIndex.

Let’s start with **Humidex formula**. You’ve seen a heat advisory but a formula advisory?

This formula is extremely long and tedious to read. It may cause dizziness, exhaustion, confusion, etc. Seek professional help if you feel any of these symptoms.

By entering a few carriage returns we can isolate each nested IF. It’s a bit easier to read.

Upon further examination I noticed that this part repeats several times:

(((-42.379+2.04901523*D4+10.14333127*C4-0.22475541*D4*C4-0.00683783*D4*D4-0.05481717*C4*C4+0.00122874*D4*D4*C4+0.00085282*D4*C4*C4-0.00000199*D4*D4*C4*C4)-32)*5/9)

I put it in a named range called ‘hx’. I also created named range ‘cnvt’ to convert Celsius to Fahrenheit.

**The humidex formula below is now much easier to read!**

You’ll have to also audit the named ranges but it’s worth it!

Now let’s look at the **HeatIndex formula**.

This is from **Dick Kusleika’s Excel site.** I can’t think of a way to make this easier to read, can you?

I definitely agree with Dick’s point below!

People have been complaining about the excessive heat for a week around here. Not me. It wonâ€™t be long until Iâ€™m shoveling my driveway, so Iâ€™m counting my blessings.

I’ve enjoyed this warm summer. Today (Aug 10) had a high of 23C, 41% humidity and a cool breeze (much cooler than most days in July!)

After summer is nice fall weather. Then in the winter we will be complaining about the wind chill factor (maybe I’ll calculate that too!) and dreaming of hot summer days!

* What is your definition of heat?* Many from the north of Canada consider southern Ontario summers to be unbearable. But those of you from warm climates would laugh at us in Canada. But then again if you visited Canada in the middle of our winter you would be in shock and we would know what to do

The overall “how we feel” calculations have different variations. Also, we all experience heat differently depending on our tolerance (i.e. health, age), intensity of our outdoor activities, etc.

Here’s some **interesting info** regarding working outside in the heat (Canadian government). My Excel file has various related links.

My name is Kevin Lehrbass. I’m a Data Analyst and I live in Markham Ontario Canada.

Right now it’s summer and it’s been hot (several 30C + days).

Our climate varies a tremendous amount from winter to summer. During winter the temperature can go all the way down to -30C (I live in the southern warmer part of Canada!) but usually it’s between 5C and -20C.

In winter we have to clear our driveways (or pay someone) but the city clears the roads and sidewalks. In Markham we don’t have to shovel the roof of the house but apparently in some parts of Canada that’s necessary. Here the temperature rises enough to periodically melt the snow on the roof.

I’m going to enjoy the last part of summer being in my backyard without putting on a coat or shoes!

]]>(download Robert’s amazing **Excel ChessGames Viewer**)

It’s rare that Chess & Excel overlap! * What should I do first?* Audit formulas? Review games?

See how to add a new game and how to review the moves on the board.

Let’s review a classic game! Below we see sheet ‘Board’.

Select a game: in cell B4 I selected ‘Kasparov’s Brilliancy’.

See the moves: click the “**^**” spinner button on the right.

The next move is the brilliant move! **Can you see it?**

Hold spin buttons to quickly cycle through moves or enter sequence number in the cell K6.

Everything starts with the game you select in cell B4. Cells B5 & B6 retrieve game details.

In cell B9 we see this key formula:

=LOOKUP(IFERROR(LOOKUP(2,

1/(CHOOSE(MoveChoice,WhiteMoves,BlackMoves)=B$8&$A9),

CHOOSE(MoveChoice,WhiteLabels,BlackLabels)),”ET”),PieceIcons)

There are two LOOKUP functions in this formula. Let’s examine the inner LOOKUP.

LOOKUP’s **lookup_value** is hard-coded to 2 (I’ll explain later).

1/(CHOOSE(MoveChoice,WhiteMoves,BlackMoves)=B$8&$A9) is the **lookup_vector** (where we look).

Select **lookup_vector** and press F9 key to see this:

Why so many errors? Because of =B$8&$A9Â Only the current cell’s a8 co-ordinate matches the result of CHOOSE(MoveChoice,WhiteMoves,BlackMoves). You’ll see a 1Â above in the 19th position.

CHOOSE(MoveChoice,WhiteLabels,BlackLabels) is the **result_vector** (answer we retrieve).

Select **result_vector** and press F9 key to see this:

The **lookup_value** is hard-coded to 2. We won’t find 2 in **lookup_vector** results so LOOKUP defaults to last value of 1 (19th position). Answer is **BR** (position 19 of results_vector) that’s used in the outer LOOKUP function!

=LOOKUP(“BR”,PieceIcons) look for BR(black rook) in named range PieceIcons (=Board!$L$9:$M$21)

To get all the way back to the raw data (sheet ‘Games’) you’ll have to audit these named ranges found inside the double LOOKUP function:

- MoveChoice
- WhiteMoves
- BlackMoves
- WhiteLabels
- BlackLabels

Here are some auditing tips:

- click inside formula bar to see referenced cells
- unhide columns L & M (to see chess icons)
- note spinner button values hidden underneath it
- use F9 key on each part to see results (then press ‘Esc’)
- audit named ranges carefully

There are 45 named ranges. Select *Formulas / Name Manager*. Here’s a sample:

Starting in column B each column is a game with moves starting in row 8. This is modern chess notation. Each row contains a move from white and black.

Column F’s game is called ‘Amazing Nakamura’. I played through the moves and IT IS amazing!

Cell B17 (sheet Board) displays chess piece material advantage. Note: a material advantage doesn’t necessarily mean a player is winning.

=CHOOSE((PtLd>-1)+(PtLd>0)+1,”Black”,”None”,”White”)&” has a”&

IF(PtLd,” “&ABS(PtLd)&”-“,”ny “)&

“point lead in chesspieces.”

Formula above uses named range PtLd (sheet Pieces) where the calculation happens. PtLd formula is:

=SUM(COUNTIF(C5:J12,

{“B”,”W”}&{“P”;”N”;”B”;”R”;”Q”})*

{-1,1}*{1;3;3;5;9})

This calculates the value of the pieces.Â See this **post** for a detailed explanation.

Robert H. Gascon is Certified Public Accountant from Quezon City, Philippines.

See his Microsoft tech community **profile**. Robert is a valued contributor meaning that he answers a lot of questions posted by Excel users.

Robert has an incredibly deep knowledge of Microsoft Excel.

Robert has shared alternative solutions on my blog. I’ve learned a lot from him. Thank you Robert!

- how-many-unique-list-1-names-found-in-list-2
- sorted-data-validation-list
- largest-number-inside-alphanumeric-string
- dynamic-ranges-using-index-function
- what-is-this-formula-doing
- concatenate-values-to-create-a-key-in-excel
- allocating-costs-in-microsoft-excel

My name is Kevin Lehrbass. I’m a Data Analyst. I live in Markham (Canada).

In 2018 I visited New York City. In central park I found outdoor chess tables and an indoor chess club.

I’ve played chess since I was 11. I was on the chess team in high school. Chess is fascinating and it’s great mental exercise. In the 90s I discovered Excel. I’ve been hooked ever since that day!

And…July 20th was **International Chess Day!**

The steps we create in Power Query are translated into M code (Power Query language). Understanding it and modifying it requires practice!

In this **post** XLarium shared an alternative solution (thanks!) to create a Cartesian product (all text combinations between multiple lists). Let’s start by auditing his solution.

First step is the same: load all 3 tables into power query. But he solves it with only 1 query (I used 2). Click ‘Advanced Editor’ to see his M code:

let

Source = Colors,

#”Removed Columns” = Table.RemoveColumns(Source,{“Dummy”}),

#”Added Custom” = Table.AddColumn(#”Removed Columns”, “Temp”, each Sizes),

#”Expanded {0}” = Table.ExpandTableColumn(#”Added Custom”, “Temp”, {“Size”}, {“Size”}),

#”Added Custom1″ = Table.AddColumn(#”Expanded {0}”, “Temp”, each Animals),

#”Expanded {0}1″ = Table.ExpandTableColumn(#”Added Custom1″, “Temp”, {“Animal”}, {“Animal”})

in

#”Expanded {0}1″

Let’s review it row by row

Source = Colors,

He references the Colors query (the loaded table).

#”Removed Columns” = Table.RemoveColumns(Source,{“Dummy”}),

His approach doesn’t need a Dummy column so he removes it.

#”Added Custom” = Table.AddColumn(#”Removed Columns”, “Temp”, each Sizes),

The current step refers to the previous step hence:Â #”Removed Columns”.Â Â

Table.AddColumnÂ is obvious but the end part “Temp”, each Sizes puzzled me. So I closed the Advanced Editor and examined ‘Added Custom’ under APPLIED STEPS.

I clicked the gear icon for step ‘Added Custom’.

Even-though ‘Color’ is the only available column he uses **=Sizes** to reference query Sizes!

The result is this:

**What is this?**

Each row in field ‘Color’ gets the entire ‘Sizes’ query (‘Table’) !!

Row 1 (‘Blue’) gets each row from query ‘Sizes’. Repeat for each row.

#”Expanded {0}” = Table.ExpandTableColumn(#”Added Custom”, “Temp”, {“Size”}, {“Size”}),

This long code simply means the double arrow button (right of ‘Temp’) was clicked!

Result of expanding field ‘Temp’ is all combinations of ‘Colors’ & ‘Sizes’ (24 total rows) !

Here we see a sample.

6 colors X 4 sizes = 24 total rows

#”Added Custom1″ = Table.AddColumn(#”Expanded {0}”, “Temp”, each Animals),

Once again XLARIUM uses “Temp” field to create multiple rows for each single row!

#”Expanded {0}1″ = Table.ExpandTableColumn(#”Added Custom1″, “Temp”, {“Animal”}, {“Animal”})

And expanding this gives us the final result of 72 rows!!!

**Why would I modify his M code?**

His solution doesn’t use Dummy columns so I removed them in the original data (sheet ‘Inputs’).

After a refresh Power Query realizes dummy columns don’t exist. The code doesn’t work.

Below we see the original M code. I’m going to modify it !

let

Source = Colors,

#”Removed Columns” = Table.RemoveColumns(Source,{“Dummy”}),

#”Added Custom” = Table.AddColumn(#”Removed Columns”, “Temp”, each Sizes),

#”Expanded {0}” = Table.ExpandTableColumn(#”Added Custom”, “Temp”, {“Size”}, {“Size”}),

#”Added Custom1″ = Table.AddColumn(#”Expanded {0}”, “Temp”, each Animals),

#”Expanded {0}1″ = Table.ExpandTableColumn(#”Added Custom1″, “Temp”, {“Animal”}, {“Animal”})

in

#”Expanded {0}1″

#”Removed Columns” = Table.RemoveColumns(Source,{“Dummy”}),

We remove this row of M code. We longer have Dummy columns in our source data.

#”Added Custom” = Table.AddColumn(#”Removed Columns”, “Temp”, each Sizes),

See the problem above? Step #”Added Custom” refers to previous step #”Removed Columns” that we removed. No problem, we change #”Removed Columns” to Source (query ‘Colors’).

Now we have this shorter code version of XLarium’s M code:

let

Source = Colors,

#”Added Custom” = Table.AddColumn(Source, “Temp”, each Sizes),

#”Expanded {0}” = Table.ExpandTableColumn(#”Added Custom”, “Temp”, {“Size”}, {“Size”}),

#”Added Custom1″ = Table.AddColumn(#”Expanded {0}”, “Temp”, each Animals),

#”Expanded {0}1″ = Table.ExpandTableColumn(#”Added Custom1″, “Temp”, {“Animal”}, {“Animal”})

in

#”Expanded {0}1″

**I now fully understand XLARIUM’s “Temp” column concept to create a Cartesian product! Thanks XLARIUM!**

My name is Kevin Lehrbass. I’m a Data Analyst. I live in Markham Ontario Canada.

I have 2 dogs. This is Cali She was upset that I was working on this post (on the weekend).

Don’t worry…I spent time with her and Fenton. It’s been hot lately and Cali loves sunning on the deck in the backyard. Fenton loves running in circles.

]]>

(Download:Â **SOLUTION Excel file**,Â **PRACTICE Excel file**)

Cartesian product creates all combinations from multiple lists. In this post I’ll use Power Query!

In sheet ‘Inputs’ we have **6 colors, 4 sizes, and 3 animals** giving us **72 combinations.**

(see * BE CAREFUL! *section below if you have thousands of combinations).

**1 – Load 3 tables into Power Query **(from sheet ‘Inputs’).

We need a ‘Dummy’ column with a 1 in each row (I’ll explain later).

- Select any cell within a table
- On the ribbon select ‘Data’ and ‘From Table/Range’
- At top left click ‘Close & Load’ drop down arrow, select ‘Close & Load To’
- Select ‘Only Create Connection’ (as seen below)
- Repeat steps to load other tables

**2 – Merge the Queries.** Use loaded tables to create all combinations.

The 3 loaded tables as queries.

2 new queries will create all row combinations.

We’ll start by combining Colors & Sizes. Highlight queries Colors & Sizes.

Click drop down arrow for ‘Merge Queries’ and select ‘Merge Queries as New’.

Details for the 1st merge:

- Select Sizes in 1st drop down list and Colors in the 2nd
- Highlight Dummy fields in both tables
- Select join kind ‘Left Outer’
- Click OK and name it ‘
**Merge1_ColorsSizes**‘

Click double arrows (Colors column) to expand to all rows.

Now you see all combinations for Sizes and Colors.

2nd and final query. Highlight Animals and Merge1_ColorsSizes

Click drop down arrow for ‘Merge Queries’ and select ‘Merge Queries as New’.

Details for the 2nd merge:

- Select Animals in 1st drop down list, Merge1_ColorsSizes in the 2nd
- Select Dummy fields in both tables
- Select join kind ‘Left Outer’
- Click OK and name it ‘
**Merge2_AnimalsMerge1**‘

Click double arrows (top right) to expand to all rows.

You’ll now see all 72 rows but let’s remove column ‘Dummy’. Right click on column Dummy and remove (we no longer need it).

Now you should see 3 columns and 72 rows!

**3 – Export Back to a Sheet.**

Select query Merge2_AnimalsMerge1.

Top left of screen select drop down arrow on ‘Close & Load’ button, select ‘Close & Load To’

Select ‘Table’, ‘Existing worksheet’ and a destination cell.

Normally we’d have unique IDs in a table (one side) and then repeating IDs in another table (many side). Example: Product table has a row for each product we sell. Sales table has a row for each sale (products sold many times).

But…here we use the 1s in the Dummy fields so that each single row in the first table matches all the rows in the second table. It’s known as a ‘Many to Many’ relationship. It’s usually bad news but here we intentionally use it to get all combinations between these tables.

**!BE CAREFUL!**

**Be careful if your tables have thousands of records**. **If you have 2 tables and each has 1000 rows that’s 1000000 rows!Â **

You could potentially freeze and crash Excel if you have too many combinations! I have seen database queries that should have a join but don’t! This creates an unintentional Cartesian product that can take many hours or days to run!

I learned this technique from **Power Query Academy** (Ken Puls & Miguel Escobar). **Disclaimer:** iâ€™m a student and an affiliate.

Here is the **Excel file** that uses XLarium’s solution (seen below in comments section). His solution doesn’t require the Dummy column with the 1s. Thanks for sharing!

Until I can quickly apply a concept on a daily basis I don’t consider it to be part of my active skill set. It’s more like an awareness that something is possible. But now I can quickly use Power Query to create all combinations and it’s MUCH EASIER than a formula or vba solution. My Excel file includes a tedious formula solution. See this post for a **Pivot Table** solution.

Note that in this example we have 3 tables so we need 2 queries. With a limited amount of tables Power Query is the fastest solution. It would be rare to get all combinations from many tables. If that’s necessary I would contact a vba programmer.

My name is Kevin Lehrbass. I’m a Data Analyst. I live in Markham Ontario Canada.

Away from data I sometimes visit museums. In May I visited an impressionist exhibit at Toronto’s **AGO**.

I should visit the **ROM’s Rembrant exhibit** this summer!

Here you see me with Mondrian Art that I saw in New York last year (**only a nerd would create Mondrian art in Excel**).

**Sum cells that are found in both ranges!**

Cells found in both ranges are highlighted green (using conditional formatting).

**=SUM(C10:G24 E3:I14)**

Include both ranges with a space (NOT a comma) between them!

The space tells Excel we want the intersection of the ranges. Other functions (Min, Max) also work.

Sheet ‘CHALLENGE’ compares the easy solution with a tedious/complex solution.

**Sheet ‘MORE FUN!’ is proof that I’m a Excel nerd **Use arrows to change range dimensions.Â I used formulas inside conditional formatting to create range borders and color overlapping cells green.

I learned this trick from **Paul McFedries book ‘Formulas and Functions’**

I’ve read 2003 & 2010 editions. This is the current edition.

If you are past the basics then I highly recommend this book! I’ve learned so much from this book and I review it often.

The beginning chapters include some essential basic tips and concepts. Further on you’ll find advanced concepts:

- Chapter 12 Working with Statistical Functions
- Chapter 16 Using Regression to Track Trends and Make Forecasts
- Chapter 17 Solving Complex Problems with Solver
- Chapter 19 Building Investment Formulas

My name is Kevin Lehrbass. I’m a Data Analyst.

Yes…I challenged someone a few years ago to solve this. I could see the smoke rising from the effort. The solution worked but was complex.

Upon seeing the easy solution I detected a “you got me” gaze followed by awkward silence. I won’t use this challenge again.

]]>