(download my **Excel file**)

The VBA code instantly refreshes when new entries are added. Perfect!

*What about a formula solution?*

Scroll to the comments section of his **post.** There’s a suggestion to use a dynamic array! These are being tested (365 insider edition) so I created a formula solution that works in all versions.

My solution contains:

- city name input in field ‘ciudades’
- four helper formula fields (steps 1 to 4)

How does it work?

- Rank =COUNTIFS([ciudades],”<=”&[@ciudades]) ‘A Coruna’ = 1, ‘Zaragoza’ = 6(last)
- Counter =ROW([@ciudades])-ROW(Table13[[#Headers],[ciudades]]) basic counter
- Match =MATCH([@Counter],[Rank],0) find Counter value in Rank
- Sorted =INDEX([ciudades],[@Match]) index to get sorted city via Match
- Data Validation connects to a named range that references step 4 Sorted

Add a city below ‘Valencia’. The Data Validation list connects to a named range and updates instantly.

The helper columns are light and easy to audit. When you add a city the table, including all formulas, automatically expands!

Both the vba and formula solutions are worth considering.

*What about a Power Query solution?*

Sure. Power Query is an amazing tool that could easily load the ‘ciudad’ text, sort it, and return it back to the sheet.

There’s one issue…if you add/modify city entries you need to refresh the query.

Using ‘Worksheet_Change’ the vba code updates automatically based on any addition or modification. The formulas are also automatic.

* Is Power Query a bad solution?* Not necessarily. If you had a large amount of data and didn’t want (a) heavy formulas or (b) vba code then Power Query could be the perfect solution! Power Query would load the data, do all the necessary steps, and then quietly drop the answers back into the sheet.

**excelforo.blogspot.com** is one of the best Spanish Excel blogs that you’ll find! I can read Spanish fairly well so when I read Ismael’s posts my Excel and Spanish hobbies collide! Coool!

Check out Ismael’s **Facebook page**!

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

I saw a friend working on an Excel model back in 1996. I was hooked for life!

It took awhile to get into the workforce…but it’s been an amazing ride!

]]>(Download my **Excel file**)

Column B has the count. Column C has the weight. Weighted average formula is:

**=SUMPRODUCT(B2:B12,C2:C12)/SUM(B2:B12)**

**12.05** is the answer.

Why can’t we just use a normal average?

If we average the numbers in column C we get an average of 14.0

BUT….it wouldn’t fairly represent our group of dogs.

Look at Pic 1, does an average of 14.0 look right???

Remember: 1 dog weighs 8 pounds, 7 weigh 9 pounds, 10 weigh 11 pounds, 11 weigh 12 pounds etc.

=AVERAGE(C2:C12) ignores the fact that most dogs weigh 9, 11, or 12 pounds (that’s 28 of 40 dogs). Only 7 dogs weigh 14 or more pounds.

Column D below helps to visualize this. I changed the font size to reflect their weight.

This is our weighted average formula:

**=SUMPRODUCT(B2:B12,C2:C12)/SUM(B2:B12)**

Let’s examine each part separately:

**SUMPRODUCT(B2:B12,C2:C12)**

SUMPRODUCT does this (1 dog X 8 pounds) + (7 dogs X 9 pounds) + (10 dogs X 11 pounds) etc **=482**

**SUM(B2:B12)**

SUM is simply counting the dogs. **=****40**

**SUMPRODUCT (482)** divided by **SUM (40)** gives us the correct weighted average of **12.05**

We were given the summary of the original data(Pic 1). Let’s **recreate the data!**

**Step 1 Cumulative Sum: **column A has a cumulative sum (+1) of column B dog count values. This creates binning groups.

**Step 2 Counter: **a sequential counter from 1 to 40 (40 dogs). Represents dog #1, dog #2, dog #3, etc.

**Step 3 Binning: =MATCH(M2,$A$1:$A$13,TRUE) **finds each counter value in column A. TRUE (approximate match) **not** FALSE (exact match) bins each counter number.

Pic 4 shows that dog #1 weighs 8 pounds. Dogs 2,3,4,5,6,7,8 all weigh 9 pounds (group or bin 2).

Look at counter value of 9. Dog #9 falls into bin 3 and has a weight of 11 pounds.

**The Proof:** *Use the normal average on column O. It’s the same as the weighted average!*

How did I create it?

I used formula =REPT(“õ”,B2)

Cell font = Webdings

I manually changed the font size (vba would be better!)

My inner nerd took over my body:

I changed the formula to: =REPT(VLOOKUP($V$1,’Animal List’!$A$2:$B$5,2,0),B2)

In cell V1 select from a list (maybe you have pet squirrels !!)

NOTE: if you increase the dog counts in column B then extend formulas in columns M,N, and O.

Watch this **video** from Microsoft.

Cali (on the right) weighs 10 pounds and Fenton weighs approximately 14 pounds (he wiggles a lot on the scale at the vet).

That’s me in the middle. I weigh a lot more! My name is Kevin Lehrbass. We live in Markham Ontario Canada.

I’ve been a Data Analyst since 2001. Microsoft Excel is my favorite software but Cali & Fenton get mad at me if I spend too much time in Excel.

Their hobbies: getting treats, barking at squirrels, naps with me on the couch.

]]>

(download my **Excel file**)

Even if your vlookup syntax is correct it might only be telling part of the story. ** HUH**?!

* Vlookup will only retrieve the first answer*. What if your lookup_value is found multiple times in your data-set? Which answer is correct?

Assuming that your lookup_value is only found once is a dangerous assumption.

I can’t examine every row in a dataset so I use various methods to double check my results.

I often use countifs to confirm how many times the lookup_value is found in the data-set. * If it’s only found 1 time then vlookup works*.

There are other ways to verify if you have unique values in a column:

**Pivot Table**put lookup_value column into row label area and also in values area as a count**Remove Duplicates**make a copy of the column and remove the duplicates. If nothing is removed there weren’t any duplicates**Conditional Formatting**highlight the duplicates**Formula**compare =COUNTA(Data!A2:A27) with =SUM(1/COUNTIFS(Data!A2:A27,Data!A2:A27)) (array formula)**Find**Excel’s find feature can search for a specific lookup_value (shortcut = ‘Ctrl F’)

Did I miss any?

If countif shows multiple matches what should we do?

- The first match wins (regular vlookup or index/match)
- The last match wins =LOOKUP(1,1/(Data!$A$2:$A$27=$C6),Data!$B$2:$B$27)
- Create a
**concatenated key**to properly identify the value

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

I live in Markham Ontario Canada.

When working with data assumptions are dangerous.

Over the years I’ve found many ways to double check results even when I’m in a hurry.

]]>

We want the CAGR for 2006 to 2013 (sheet ‘CAGR answer proof’ in my **Excel file**).

- logic
**=((EndYearAmount/StartYearAmount)^(1/NumberOfYearIntervals))-1** - formula
**=((C11/C4)^(1/7))-1** - answer
**0.032926657892244**in cell H7

We’ll use column D to increase original 302.50 amount in 7 steps (years or periods)

- Cell D4 has formula
**=C4**(cell C4 is 2006 amount or year 0 amount) - Cell D5 has formula
**=D4*(1+$H$7)**Drag it down to cell D11 - Cell D11 calculated amount = original ending amount in cell C11

In step 2 (cell D5) we add 1 to our CAGR answer to get 1.032926657892244 so that column D amount increases as we drag formula down.

CAGR formula (Compound Annual Growth Rate) is used to analyze and compare investments.

The CAGR formula below does all steps in a single formula. The pic above shows you what happens inside the formula year by year. Pic below goes into more detail.

**=((EndYearAmount/StartYearAmount)^(1/NumberOfYearIntervals))-1**

CAGR * doesn’t* take the difference between EndYear and StartYear amounts divided by number of years. It would be easier to add 11 to starting amount 302.50 seven times to end up with 379.50 (columns G & H) but that’s not a CAGR. Let’s walk through the compounding nature of CAGR:

- Column E shows yearly increases: (1+CAGR) X previous amount. Cell E11 = D11 year end value
- Column F yearly increase difference (312.46 – 302.50 = 9.96 in cell F5) is a compounding amount (starts smaller, ends larger). Cell F17 average of F5 to F11 = 11.
- Column F has compounding amounts, column G is always the same amount

Does this help explain CAGR’s compounding nature? In my Excel file see sheet ‘what CAGR does’. All 3 examples show CAGR starting smaller and ending larger. The mid point (year 4 in this example) is almost identical to the average. The charts show this well.

The most common pitfall is incorrectly entering the number of years.

If we want the CAGR for 2006 to 2013 that’s 7 intervals NOT 8! I’d suggest altering the formula to this:

**=((EndYearAmount/StartYearAmount)^(1/(EndYear-StartYear)))-1**

When replacing the text above with cells references it looks like this:

**=((C11/C4)^(1/(B11-B4))-1) ** dollar amounts in column C, years in column B.

CAGR is one of many financial calculations (i.e. IRR, MIRR, NPV). Each have their uses and limitations.

Would you like to dive deeper into the math? I recommend these articles:

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

It wasn’t my dog Cali who asked me to prove that my CAGR was correct. But it was a real question from just last week. We should question how a solution works. Imagine all the errors that would be eliminated if all solutions were reviewed carefully.

Fenton and Cali went to the vet this past weekend for shots and and a TRIM. They look so different with short hair

]]>

Ankur Shukla’s **comment** reminded me that the fastest way to solve this challenge is to use FlashFill! If the pattern is consistent let FlashFill solve it! Type in the pattern (usually 1 or 2 entries is enough), click ‘Data’ and ‘Flash Fill’. Done!

The **array solution** is slow to calculate on a large data-set but it’s beautiful! And sometimes we need a dynamic formula (Power Query requires a refresh, Flash Fill needs rerunning). Arrays should be used sparingly like a fine wine but they can calculate the impossible and I love them! (see end of post for alternative array)

**Kunle SOPEJU** sent me his Excel Power Query solution. It’s amazing! ** WHY ? **(see end of post for alternative PQ solution)

If we had thousands of rows of data the array would be heavy. Why use so much calculation effort on extracting the largest number in each cell when Power Query can do the heavy lifting and drop the answers back into the sheet! Also, if we learn Power Query we can automate other tedious tasks!

Download **the Excel file** and follow my detailed explanation of Kunle’s Power Query solution.

I can confidently use basic features in Power Query but I’m not an advanced user (yet). To learn more I’ll audit Kunle’s solution!

**Input & Output**

We start in worksheet “**sheet1**” (seen above).

The blue table is the original data. The green table is what Power Query exports back to the sheet.

We see the largest number results in column D! Let’s audit the steps inside Power Query.

**Opening Power Query**

Let’s enter the magical world where all the action takes place!

- Select any cell in the green table
- On the ribbon select ‘Query Tools’ and ‘Edit’

**First Glance**

The original untouched data is below on the left (column ‘AlphaNum’).

PROPERTIES shows the query name: “**Stepwise – Largest Number in String**“

APPLIED STEPS lists each step. Oyekunle has clearly labeled the steps for us

Next is to explore the details of each applied step.

**STEP 1 “Source”**

= Excel.CurrentWorkbook(){[Name=”Table6″]}[Content]

Pic above shows us that the data is loaded from “Table6” (before any steps take place).

**STEP 2 “AddCol – Txt2List”**

Click Applied Step **AddCol – Txt2List** to see this:

We can see each step’s full code in the formula bar but it’s a bit confusing.

**There’s 2 ways to dig into the details to help understand what’s going on:**

(a) click the circular gear icon to the right of this step’s name

Now you should see this “Custom Column” box. This step uses this text function:

=Text.ToList( [AphaNum] )

**Tip**: click **here** to see Microsoft’s definition & example of Text.ToList

(b) in column “Txt2List” click the white space next to “List” in any row.

You’ll see each individual character split out into a vertical list like this:

**STEP 3 “AddCol – Replace Txt with Spaces”**

Click applied step “AddCol – Replace Txt with Spaces”. Click the gear to see the function:

List.Transform( [Txt2List] , each if Value.FromText( _ ) is text then ” ” else _ )

It looks at each value in the list. If it’s a text then it becomes a space.

In column “Transform List” click any white space beside “List”. Letters are removed!

**STEP 4 “Add Col – CombineText”**

Click applied step “Add Col – CombineText”

Clicking the gear reveals: Text.Combine( [TransformList] )

Spaces and numbers in the vertical list are flipped back into a horizontal cell.

**STEP 5 “Add Col – SplitText by Spaces”**

Click applied step “Add Col – SplitText by Spaces”

Clicking the gear reveals: Text.Split( [CombnTxt] , ” ” )

Numbers separated by spaces in each cell are now split apart in this new list. COOL !

In column “Split Text” click any white space beside “List” to reveal:

The list contains all the individual numbers! (but they are stored as text)

***We are almost finished now!***

**STEP 6 “Add Col – Transform Txt to Numbers”**

Click the gear to see function: List.Transform( [SplitTxt] , each Value.FromText( _ ) * 1 )

Each text number is multiplied by 1 to convert into a real number.

**STEP 7 “Add Col – Obtain Largest Number in List”**

Function List.Max ( [#”ListTransform – Txt2Number”] ) grabs the largest number in the list!

**STEP 8 “Removed Other Columns”**

Now we have our final answer so we can hide all the intermediary steps.

**Send Query Answers to Sheet1**

In the top left of the ‘Home’ tab Kunle clicked “**Close & Apply**” drop down (NOT the icon above) and then “**Close & Load to…**” to select exactly which sheet and cell to put the answers!

Currently, Oyekunle offers his services as a Resource person to Training and Consulting outfits in Sales and Data Analysis. He is a Faculty Member/Consultant with **AutusBridge Consulting Ltd** (Training & Consulting) in Lagos, Nigeria. He is a Certified Tutor of both Institute of Sales Management, United Kingdom. (ISM-UK) and Cambrigde Professional Academy, UK.

He is particularly interested in bridging the Data Science Gap. His favorite data analysis tools and apps is MS Excel, Power Query with M-Language, Power Pivot with DAX and of course Power BI.

Oyekunle has worked in Pharmaceuticals, FMCG and Telecommunications both in Nigeria and Ghana.

Ankur is an accountant and Excel guru from Lucknow, Uttar Pradesh, India. You can find him on **Linkedin** and **ExcelForum.com**

Thanks Ankur for all the comments & suggestions you’ve made on my YouTube channel!

Thank you **Kunle** for your solution! Auditing it has helped my understand Power Query Lists!

**What’s the BONUS?**

Inside Power Query click ‘Queries’ (left side). We see Oyekunle’s “Stepwise – Largest Number in String” query that we just audited.

Audit other queries & custom functions like “fnLargestNumberInAString” to learn more!

Instead of writing each step individually you could open the ‘Advanced Editor’ and write the M code.

This requires a lot of practice but some can do it! Here is Oyekunle’s M code:

Source = Excel.CurrentWorkbook(){[Name=”Table6″]}[Content],

#”AddCol – Txt2List” = Table.AddColumn(Source, “Txt2List”, each Text.ToList( [AlphaNum] )),

#”Add Col – Replace Txt with Spaces” = Table.AddColumn(#”AddCol – Txt2List”, “TransformList”, each List.Transform( [Txt2List] , each if Value.FromText( _ ) is text then ” ” else _ )),

#”Add Col – CombineText” = Table.AddColumn(#”Add Col – Replace Txt with Spaces”, “CombnTxt”, each Text.Combine( [TransformList] )),

#”Add Col – SplitText by Spaces” = Table.AddColumn(#”Add Col – CombineText”, “SplitTxt”, each Text.Split( [CombnTxt] , ” ” )),

#”Add Col – Transform Txt to Numbers” = Table.AddColumn(#”Add Col – SplitText by Spaces”, “ListTransform – Txt2Number”, each List.Transform( [SplitTxt] , each Value.FromText( _ ) * 1 )),

#”Add Col – Obtain Largest Number in List” = Table.AddColumn(#”Add Col – Transform Txt to Numbers”, “LargestNumber in String”, each List.Max ( [#”ListTransform – Txt2Number”] )),

#”Removed Other Columns” = Table.SelectColumns(#”Add Col – Obtain Largest Number in List”,{“AlphaNum”, “LargestNumber in String”})

in

#”Removed Other Columns”

Select ‘Home’ at the top and then ‘Advanced Editor’ to see this code.

It takes practice to understand M code. Auditing the steps carefully makes it easier. Remember that:

- a step starts with “#”
- each step refers to the previous step
- values were juggled back & forth between cells and lists
- various functions were used
- Oyekunle clearly renamed each step (easier to audit !)

I’ve been taking this amazing **course** taught by Ken Puls and Miguel Escobar. I’ve learned so much!

Disclaimer: i’m a student and an affiliate.

YouTuber ‘**GaribaldiInTheMaking**‘ suggested this alternative array formula that uses the versatile AGGREGATE function. It’s a longer formula that might be faster!

**Daniel Choi** (his **Excel blog**) shared three Power Query solutions with me! Thanks Daniel! Unfortunately it doesn’t work on my version of Excel 2016 but feel free to **download** it.

In the comments below Bill Szysz suggested a one step Power Query solution:

let

Source = Table.AddColumn(Table.TransformColumnTypes(Excel.CurrentWorkbook(){[Name=”Table6″]}[Content],{{“AlphaNum”, type text}}), “Largest”, each List.Max(List.Transform(Text.Split(Text.Combine(List.Transform(Text.ToList([AlphaNum]), each try Text.From(Number.From(_)) otherwise ” “)), ” “), each try Number.From(_) otherwise null) ) )

in

Source

I think both the step by step method by Kunle and Bill’s one step method are amazing! Sometimes we need to break things down into steps to see exactly how they work. And then it’s also great to know how to create a short compact solution.

My name is Kevin Lehrbass. I live in Markham Ontario Canada.

These are my dogs Cali and Fenton. They sit with me when I write my blog posts. They know when I need a break from my laptop

I’ve been a Data Analyst since 2001. My favorite software is Microsoft Excel. I’m currently learning Power BI.

]]>

We start with this:

and we need to re-arrange it into this:

You’ll see amazing Power Query solutions in the comments section of **Chandeep’s post** plus a Dynamic Array solution! I solved it using traditional formulas.

Download my **Excel file** and follow along.

**Step 1 – What’s the pattern?**

Each group starts with a Manager Code, Manager name, followed by one or more Employee names.

This formula adds a position number at the beginning of each group:

=IF(ISNUMBER(RIGHT([@Data],1)+0),ROW([@Data])-ROW(Table1[[#Headers],[Data]]),””)

**Step 2 – List Start of Each Group**

I used a counter and the small function =SMALL(Table1[Pos ‘#],D5) to get the position numbers (removing spaces as seen above).

**Step 3 – Manager eCode**

A simple Index function referencing Step 2 to create a vertical list of the Manager eCodes: =INDEX(Table1[Data],E5)

**Step 4 – Manager & Employee Names**

Get the names after the Manager eCode. Stop when the next group starts. I used a 2nd counter (column headers) and this formula to know when to stop extracting names:

=IF($E5+G$4>=$E6,””,INDEX(Table1[Data],$E5+G$4))

The end result looks like this:

Here’s an **older post** where I unstacked data with the one and only Oz du Soleil!

Chandeep is from Gurgaon, India. Before venturing into the Excel training & consulting world he worked at an investment bank. His blog is **https://www.goodly.co.in/**

Check out Chandeep’s **chart quiz game**. **I scored 6 out of 7**

My name is Kevin Lehrbass. I live in Markham Ontario Canada.

Excel challenges are fun!

Do you have an interesting challenge?

]]>

Before solving this we need to know the full context. Is it 200 cells? 900000 cells?

We have 1000 alphanumeric cells. With this small amount we can consider almost any approach.

Download my **Excel file.** Read below or **watch my video**.

My colleague solved this challenge with this amazing array formula:

**=MAX(IFERROR(MID(F4,ROW($A$1:$A$30),COLUMN($A$1:$Y$1))*1,””))**

(after pasting it into formula bar you need to hold Ctrl & Shift keys and then press Enter)

At first I didn’t understand it. But once I audited it I just loved it! I’ll show you why!

Let’s backup and review how we normally use the MID function. **=MID(F4,5,3)**

In cell F4, go to 5th position, extract 3 characters. We get **0lk **

Three parts: cell reference, starting point, number of characters to extract.

**But we’re going to extract multiple values from each point inside cell F4 !**

All the big action happens in this step!

- in cell G4 click inside the formula bar
- highlight
**MID(F4,ROW($A$1:$A$30),COLUMN($A$1:$Y$1))** - press F9 key (on laptop hold Fn key and press F9 key)

This is a sample of what you’ll see!

We only want pure numbers like “4”, “42”, “420” etc.

(press ‘Esc’ key to go back to the formula)

Multiply each string by 1. Text numbers convert into a number. Everything else is an error.

Adding IFERROR changes all errors to blank. We are left with just the numbers.

MAX function gives us the largest number **2324** !

Change the numbers inside cell F4 or F5 to make sure the solution works.

Q: What’s the difference between the commas and semi-colons inside the array?

A: The semi-colons are part of the vertical array created by the ROW function. The commas are part of the horizontal array created by the COLUMN function.

Each one is one dimensional but when used together a cool two dimensional array is created!

Via a google search I found vba code that solved this but the code made my head spin. I love vba but it was intense. In this case my colleague’s array formula wins!

I’m curious if anyone can solve this using Power Query (Get & Transform). Please let me know

**Update**: comments here & below **my video** provide Power Query solutions! Thanks to Daniel Choi and Oyekunle SOPEJU !

Thanks to Ankur shukla for suggesting the Flashfill solution! If the pattern is consistent flashfill’s internal logic can fill the results almost instantly after we show it the pattern.

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

I’ve been working with data since 2001 but I’m still learning so much!

I wouldn’t want to ever stop learning. I’m lucky that my job is also my hobby!

Check out my **recommended training section**.

]]>

Silly but a great way to practice VBA. Once I started playing around my curiosity took over. I tinkered around for a few hours while listening to music.

**Not** recommended as a Valentine’s Day gift unless he/she loves spreadsheets and/or programming.

Download my **Excel file** and click the robot to add a heart! Click it again!

I used the macro recorder to create basic code for:

- moving the robot
- adding a heart
- rotating a heart
- varying the heart color

I modified macro recorder code to create more powerful VBA. Examples:

The macro recorder created this:

Sub TESTcreateHeart()

‘ TESTcreateHeart Macro

‘

ActiveSheet.Shapes.AddShape(msoShapeHeart, 847.5, 168.6, 72, 72).Select

End Sub

Changing the numbers inside the brackets revealed the purpose of each one.

- 847.5 lateral position
- 168.6 vertical position
- 72 width
- 72 height

I wanted to randomize the heart location and size. I added some variables (all numbers).

Dim lateral, vertical, heartsize As Integer

Next was assigning the random numbers to each variable. Heartsize is used for width & height.

lateral = (Rnd() * 500) + 70

vertical = (Rnd() * 175) + 45

heartsize = Rnd() * 45

Now the variable names replace the original hard-coded numbers:

ActiveSheet.Shapes.AddShape(msoShapeHeart, lateral, vertical, heartsize, heartsize).Select

The macro recorder created this:

Sub TEST_Heart_Color_and_Transparency()

‘ TEST_Heart_Color_and_Transparency Macro

ActiveSheet.Shapes.Range(Array(“Heart 2”)).Select

With Selection.ShapeRange.Fill

.Visible = msoTrue

.ForeColor.RGB = RGB(255, 0, 0)

.Transparency = 0.6999999881

.Solid

End With

End Sub

I created variables redc and transp and assigned values to them.

transp = Rnd()

redc = WorksheetFunction.RandBetween(150, 255)

I also added a random tilt for the heart and code to create 3D hearts.

The main macro is Create_A_Heart found in module A_CreateHeart. Many actions are inside this macro but I also used the Call procedure to run macros in a separate vba modules. Example: move the robot let and right.

Call E_MoveRobot

This macro gets the variable value from individual cells (named ranges) in sheet Hearts. You can modify the numbers in column D!

I used named ranges instead of hard coded cell references in case I added rows or columns later on.

Sub E_MoveRobot()

Dim movebot, movebotleft, movebotright As Integer

movebotleft = Range(“Move_robot_left_amount”).Value

movebotright = Range(“Move_robot_right_amount”).Value

movebot = WorksheetFunction.RandBetween(movebotleft, movebotright)

ActiveSheet.Shapes.Range(Array(“RedRobot”)).Select

Selection.ShapeRange.IncrementLeft movebot

Range(“MoveRobotValue”).Value = movebot

End Sub

Finally, I added code to assign each heart’s variable values to cells in column J. Why? Why not.

Range(“HeartCount”).Value = Range(“HeartCount”).Value + 1

Range(“HorizontalPosition”).Value = lateral

Range(“VerticalPosition”).Value = vertical

Range(“HeartSize”).Value = heartsize

Range(“MoveRobotTotal”).Value = Range(“MoveRobotValue”).Value + Range(“MoveRobotTotal”).Value

I found these sites helpful for my VBA syntax questions:

- docs.microsoft.com/en-us/office/vba/api/excel.shapes.addshape
- docs.microsoft.com/en-us/office/vba/api/excel.shaperange.incrementrotation
- powerspreadsheets.com/excel-vba-range-object/
- excelmacromastery.com/excel-vba-range-cells/
- thespreadsheetguru.com/blog/how-to-keep-track-of-your-shapes-created-with-vba-code

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

I can still remember when I first discovered VBA in Excel. Life altering!!

These days I don’t use vba regularly but I try to keep my skills alive by building things.

]]>

It’s easier to analyze data with Pivot Tables or formulas when data has a tabular structure like a database. Each thing has it’s own column, each row is a transaction (i.e. a sale).

This is a crosstab data layout. Great for reading as a final layout. Not ideal to build a model on top of it.

We have 3 parts: Department, Date, Number. Each part should be in a separate column.

A crosstab can be unpivoted using Excel’s Get & Transform (aka Power Query):

**Load Data**

- Select any cell within your data
- On the ribbon click ‘Data’, in ‘Get & Transform Data’ section select ‘From Table/Range’

**Transformation Steps**

- Right click column header ‘Department’
- Select ‘Unpivot Other Columns’
- Double click column header ‘Attribute’, rename to ‘Date’
- Double click column header ‘Value’, rename to ‘Sales’

**Export Back To Sheet**

- In top left click ‘Close & Load’, ‘Close & Load To…’, and select a location.

The data should now look like this:

**This is a database/pivot table friendly layout.** Easily analyze this data with Pivot Tables or formulas.

Note: by default the output links to the original data. You could delete the query and keep the output.

Download my **Excel file.** Or use this **Excel file Practice** to create the unpivot steps above.

Rare exception: hours have been spent building a model on top of unpivoted data. A deadline is pending so I can answer the questions with a few formulas. Example layout:

We really only have two pieces of data: Date and Number. I decided not to unpivot this layout (see my **post**) as I could answer the questions with just a few formulas

**Could we leave the data entry layout as a crosstab and still pivot it? Yes!** We could do this:

- use Power Query to unpivot this layout
- export the results to a new sheet
- add a Pivot Table (or formulas)

If the data changes or expands we’d have to refresh Power Query and the Pivot Table. Not a best practice but it works!

Preventing the need to unpivot data is ideal. If we have the opportunity early on we can explain the tabular data layout and why it’s important.

Crosstab isn’t the only awkward data layout. There are others including:

**Single data-set split across sheets**

A single data-set is chopped into pieces and split into several sheets. It’s probably done to make it easier to read…but then trying to analyze it as a single data-set is extremely difficult. Many try using 3D ranges and other circus tricks. A dataset should be kept together in one sheet.

**Stacked Data-set**

An entire data-set is stacked in a single column. Instead of having various rows of data the rows are all rotated and stacked into this single column. Other software sometimes exports the data like this. Formulas or Power Query can be used to re-arrange this layout into a database or pivot table friendly layout. Read this **post**.

**Mini Data Blocks**

Sometimes a dataset is split into many mini datasets. Read this **post** to see how to pull it all together into a single dataset.

**Other Non Tabular Datasets**

See my previous **post** with other non tabular layouts and my recent rearranging data **post**.

My name is Kevin Lehrbass. I’ve been working as a Data Analyst since 2001.

I’ve learned how important it is to structure data before analyzing it. Yes there are many tricks (i.e. 3D ranges, array formulas, vba etc) to work around a poor data structure but starting with a proper data layout saves so much unnecessary work and stress.

In November of 2018 I visited Memphis. I visited the **Blues museum** on Main street and did a tour of Beale street including **BB King’s Blues Club**.

High level: (a) split ‘Clients Assigned’ names into columns, (b) unpivot those columns into rows.

This task is now incredibly easy thanks to Excel’s Power Query (Get & Transform) tool.

Get my **Excel file** and follow along.

**Load Data**

- Select any cell within your data
- On the ribbon click ‘Data’, in ‘Get & Transform Data’ section select ‘From Table/Range’

**Transformation Steps**

- Right click column header ‘Clients Assigned’, ‘Split column’, ‘By Delimiter’, select ‘Comma’, split at ‘Each occurence…’

- Right click column header ‘SalesPerson’ and ‘Unpivot other columns’
- Right click column header ‘Attribute’ and ‘Remove’
- Double left click column header to rename ‘Value’ to ‘Clients Assigned’

**Export Back To Sheet**

- Click ‘Close & Load’, ‘Close & Load To…’, and select a location.

Building a model on top of database layout data is much easier. However, there are some rare exceptions. If the task were simply to count the clients assigned to each salesperson use this formula:

=LEN(G5)-LEN(SUBSTITUTE(G5,”,”,””))

Or if it’s a table format use this formula:

=LEN([@[Clients Assigned]])-LEN(SUBSTITUTE([@[Clients Assigned]],”,”,””))

In the ol’ days before power query rearranging data was often painful. It’s possible to use formulas to solve this but it’s so much work. There’s also a trick to combine Text to Columns with the Alt D P pivot trick. Just a few steps but Power Query is still easier.

My name is Kevin Lehrbass. I’ve worked as a Data Analyst since 2001.

Power Query is a revolutionary tool! The basics are easy to learn but mastering advanced techniques takes practice. The vast majority of Excel users have no idea how valuable Power Query is.

Power Query is free! Starting with Excel 2016 it’s a built-in feature. Learn with me at **Power Query academy**.