Any ideas how to determine what age group an individual belongs in Excel? - vba

I have 2 columns in an Excel spread sheet.
First column header is called AGE and the second column header is called Age_Group.
The ages in the AGE column are between 18 and 45.
There could be multiple rows with same age.
I am tasked with determining what age group a certain age falls into and then print out that age group.
For instance, if someone’s age is 18, I would like to use IF statement or CASE statement to determine that age 18 is between 18 and 24 and then put that value into Age_Group column as 18-24.
If age is 19, again, it will fall into the group of 18-24 in Age_Group column.
If the age in the Age column falls between 25 and 29, then they will be in Age_Group column as 25-29.
Here is an example:
AGE AGE_GROUP
18 18-24
19 18-24,
25 25-29
28 25-29
If you would be kind to share some code, I can use it to calculate the rest till we reach 45.
I am not good with Excel VBA. Any assistance with IF or CASE statement would be greatly appreciated.

Use a vlookup. Create a two column table with the lower bound of your age range in the first column and the age range as text in the second column like so:
AGE_LOOKUP AGE_GROUP
18 18-24
25 25-29
30 30-35
36 36-37 etc..
Name this table's range as AGE_GROUP_TABLE then using the following formula to get the age group:
VLOOKUP(A1, AGE_GROUP_TABLE, 2, TRUE)
Put different ages into cell A1 and the formula will return the correct age group. The important thing to remember is to make sure that the last parameter of the VLOOKUP is set to TRUE, this makes the VLOOKUP find the nearest match.

Here is a VBA code: But surely you are better off with that Excel VLOOKUP. :)
First add module to a VBA project.
Copy the following
code.
Option Explicit
Function whatAgeGroup(ByVal i As Integer) As String
Select Case i
Case IsEmpty(i)
whatAgeGroup = "No Age Entered"
Case 18 To 24:
whatAgeGroup = "18-24"
Case 25 To 29
whatAgeGroup = "25-29"
Case 30 To 34
whatAgeGroup = "30-34"
Case 35 To 39
whatAgeGroup = "35-39"
Case 40 To 44
whatAgeGroup = "40-44"
Case Is >= 45
whatAgeGroup = "45 and Above"
Case Else
whatAgeGroup = "WhatGroup?"
End Select
End Function
enter the function name in a cell and enter, as per the image shown.

As the idea of a Table was causing some confusion I thought I would also share my favourite trick of a self contained, table free, VLOOKUP using an embedded array. So for the current problem it would look something like this:
VLOOKUP(A1, {18,"18-24";25,"25-29";30,"30-35";36,"36-37"}, 2 TRUE)

While the vlookup solution is excellent, you can also do that with a PivotTable. Make sure the age is the row heading, then right click the Age "square" and select Group. This is avery easy and dynamic.

Related

INDEX MATCH formula in Excel returning incorrect results in some cells and correct results in others

Before I start I will say that I cannot post the actual spreadsheet as it contains confidential data.
I have a spreadsheet to record sports carnival data and calculate House and age champions.
The spreadsheet has columns F "gender", K "name", L "age" and N "score".
I am using the following formula to generate champions in each age and gender group (eg 12 year old female, 12 year old male, 13 year old female, etc)
=INDEX($K$2:$K$1000,MATCH(MAXIFS($N$2:$N$1000,$F$2:$F$1000,"F",$L$2:$L$1000,"12"),$N$2:$N$1000,0))
where the "F" changes to "M" and the "12" changes to the various age groups.
The formula returns correct results for "F" "12", "16" and "17" but incorrect for "F" "13", "14" and "15". And a similar combination for the male age champions. The incorrect result 'name' is both the wrong gender and the wrong age.
I have tried several different 'fixes' including text/number alternatives and different formulas to solve the problem but the incorrect result keeps recurring.
Any help would be greatly appreciated.
Use the Formula Evaluation tool on the Formulas ribbon to step through the formula that returns "incorrect" results.
You will see what MAXIFS resolves to. You will see what MATCH resolves to.
I would assume that the number returned by MAXIFS is not a unique value, so the MATCH function finds the first match for that value, and that may be for the wrong age group and gender.
If you are using Office 365, then you have the new Dynamic Array functions. In that case, you can use
=INDEX(FILTER(K2:K10,(F2:F10="m")*(L2:L10=13)),MATCH(MAX(FILTER(N2:N10,(F2:F10="m")*(L2:L10=13))),FILTER(N2:N10,(F2:F10="m")*(L2:L10=13)),0))
The screenshot shows the formula in action. Cell Q2 shows your formula, returning the wrong result "girl4", which is a match for the result returned by MAXIFS.
Cell Q3 has the formula using Filter, which applies the same filter to the match as to the MAX function.

Sorting a range of values correctly in vba

I have the following data in a pivot table. To the left, is described a range and to the right the number of cells within that range. I would like to learn a code that correctly arranges the range in the left and color codes anything after "80-89". I have used the sort function but it doesn't seem to work. Please help.
Days Count of PR ID
"10-19" 656
"0-9" 480
"20-29" 190
"30-39" 115
"40-49" 65
"50-59" 47
"70-79" 28
"60-69" 23
"80-89" 12
"110-119" 3
"120-129" 2
"130-139" 1
"100-109" 1
"180-189" 1
Use a helper column which can then be used for the numerical sort. So in the source data add a helper column next to the days column that goes 1,2,3,4 etc ranking days - you can use a vlookup to pull in the right rank for each days group. Then use this to sort on in your pivottable. Conditional formatting can then do your colouring as well based on the helper column value.
Data with helper column and vlookup table:
Note that this would be your actual backing data before aggregating up that would have the helper column.
Pivot using helper column to order (note: you would use Count not Sum):
Conditional formatting:
Add a conditional formatting rule (to meet your requirements) using the helper column value:
Result:

(VBA) Extract and copy and paste column values for specified date range for corresponding row values

I've been stuck on this for a while now. What I need is the title - what I have is:
Sheet 1:
1 billion mostly unnecessary columns.
Column D: Values I need Column F: Column M:
Revenue Names Date
12 John 1/24/2016 2:40:02 AM
15 Sarah 3/2/2016 4:35:17 PM
14 Sarah 7/17/2016 1:50:10 PM
20 Matt 8/20/2012 4:16:12 AM
10 John 11/19/2015 5:04:05 AM
etc. etc.
Current Sheet 2: Pivot Table*
Row Label:
Sarah
Matt
John
etc.
Desired Sheet 2 Pivot Table+*
Row Label: Column __:
Revenue
Sarah 29
Matt 0 *(note: see below, but = 0 because Matts value corresponded to date 2012)
John 22
etc.
The important thing about Sheet 2 is that I would like to tell VBA to find the nearest emptiest column within the sheet, and input the values from Column D from S1 (and sum for duplicates) but only sum and extract values that range from today's date to 11 months prior. Currently I made a module to automatically create a pivot table for the next sheet, but I have wanted to add the above for a while, just stuck.
I'm also assuming I won't have to specify sum if I tell VBA to extract data for corresponding row label names? And I was thinking about putting a Begin Date and End Date cells on Sheet 2 to refer to, or using the TODAY() function somehow for the date, but not sure how to specify to extract and sum values for the date range from today to 11 months prior.
Edit: *Please note this is a watered down version of my current situation, everything is bigger so to avoid confusion, pivots are necessary, but I choose to dilute it for the sake of this issue.
Do you really need a pivot table?
If you dont, just create a new sheet with all the names, set a cell for the starting date you want to consider and do =sumifs
For example
On Sheet2 B1 you put 1/24/2016.
Then on A2 you insert the name (Sarah, for example)
On B2 you put the formula
=Sumifs(Sheet1!D:D,Sheet1!F:F,A2,Sheet1!M:M,">"&B$1)
After that just make a list of name and drag the formula beside every name.
*My excel is in portuguese so maybe the formula needs some other ajustments to work.

Excel VBA selecting data from a sorted Table

I am running into a problem in VBA in excel.
I am trying to create a participant registration program in excel for a sports tournament. One can add data like the weight, age and name of a participant. And then based on that, The participants are divided into poules named with letters A, B... until Z. I have a table which can sort these poules by letters and then for example only display the participants which are in poule A such as below
Example
Now i want to count the numbers with VBA macros of participants in the poule which is displayed by the sorted table. For example when i sort on poule A it has to return 3 and when i sort on B, it has to return 2.
Determined by the number of participants in a poule the program will print a different poule scheme, depending on the number of participants. (i have this part in VBA)
The problem is when i have a sorted table like below
Example 2
It counts all the participants, and not just the ones in B or any other sorted letter.
I have this:
Sub Count()
Dim nRows As Integer
nRows = Range(Range("A18"), Range("A18").End(xlDown)).Rows.Count
MsgBox (nRows)
End Sub
This works well if you sort A, but when you sort any other letter, it counts All the table until that letter. Eg. when you sort B, it displays 5 (Number of A + B).
I have looked on the internet for a really long time to find a solution but without succes.
I hope my question is clear and that somebody can help me.
I am assuming that you are using worksheet functions. Use Subtotal when working with filtered data.
These parameters evaluate all cells visible or hidden
1 AVERAGE
2 COUNT
3 COUNTA
4 MAX
5 MIN
6 PRODUCT
7 STDEV
8 STDEVP
9 SUM
10 VAR
11 VARP
These parameters evaluate only visible cells
101 AVERAGE
102 COUNT
103 COUNTA
104 MAX
105 MIN
106 PRODUCT
107 STDEV
108 STDEVP
109 SUM
110 VAR
111 VARP
The code does work now, except that it only counts the first letters it encounters.
So when the first column for the poules is for example A A A E A A B B E.
And i sort to A and use the count function, it only returns a value of 3 and not of 5 (because there are 5 A's)
When I sort the table to A, it looks like this (column number, poule value):
14 A
15 A
16 A
18 A
19 A
And it returns just a count of 3, have you maybe got any fixes for that problem as well?
Pictures:
sorted tabel to E
Table
Range.SpecialCells will return a range of only visible cells.
Dim rSource As Range
Dim rVisibleCells
Set rSource = Range(Range("A2"), Range("A2").End(xlDown))
Set rVisibleCells = rSource.SpecialCells(xlCellTypeVisible)
MsgBox rVisibleCells.Rows.Count

Excel VBA: Move row to a destination regardless of row count in pivot table

I am new to VBA and have very basic knowledge. I have a pivot table which calculates the count of students grouped by enrollment date and columns consists of Brand Ids
I want to move a row to the end of the pivot table and the number of rows keeps changing. I tried below code but I can use that only when number of rows in pivot table are constant. Can someone please help me to move row to the end of the table though the number of rows are not constant?
ActiveSheet.PivotTables("StudentCount").PivotSelect "'En_Date'['(blank)']", _
xlDataAndLabel + xlFirstRow, True
ActiveSheet.PivotTables("StudentCount").PivotFields("En_Date").PivtoItems( _
"(blank)").Position = 20
'In current sheet I need to move to 20 but actually 20 is not constant
ActiveSheet.PivotTables("StudentCOunt").PivotSelect "En_Date", xlButton, True
I tried below code as well but it is not working:
Dim LS as LONG
LS = ActiveSheet.PivotTable("StudentCount").TableRange2.Rows.Count
ActiveSheet.PivotTables("StudentCount").PivotSelect "'En_Date'['(blank)']", _
xlDataAndLabel + xlFirstRow, True
ActiveSheet.PivotTables("StudentCount").PivotFields("En_Date").PivtoItems( _
"(blank)").Position = "& (LS - 1)"
ActiveSheet.PivotTables("StudentCOunt").PivotSelect "En_Date", xlButton, True
Pivot Table:
Count Of Students
Date A1 A2 A3 A4 Blank Grand TOtal
blank 69 86 23 45 223
01/01/2014 2 25 3 1 31
02/01/2014 1 2 5 8 16
Grand Total 71 112 28 51 262
Hi to answer your question, you do not need VBA to do this.
The reason your pivot is behaving as such is because your Dates are actually not Dates but Dates Entered as Text. See below recreated data:
Re-entering it as actual dates will solve your problem.
So after changing the Text Dates to actual Dates, your pivot sorts your row as you like.
See below:
Hope the solution I presented helps you a bit.
Additional: If however re-entering all the dates is not convenient, try below code:
Dim i As Integer
With ActiveSheet.PivotTables("StudentCount").PivotFields("En Date")
For i = 1 To .PivotItems.Count
If .PivotItems(i) = "(blank)" Then .PivotItems(i).Position = .PivotItems.Count
Next
End With
The code above simply iterates through all the PivotItems, looks for (blanks).
It then change it's position to the last position which is equal to .PivotItems.Count.
Hope this works for you.