Public Schedule Face-to-Face & Online Instructor-Led Training - View dates & book

macro create age bands

Forum home » Delegate support and help forum » Microsoft Excel VBA Training and help » Macro to create age bands from an age field

Macro to create age bands from an age field

ResolvedVersion 2007

Sarah has attended:
Excel VBA Intro Intermediate course
Access Advanced course
Access Intermediate course

Macro to create age bands from an age field

I want create a macro that I can keep in my personal workbook to create 5 year age bands from a field that has the age. So I'd want ages 0-4, 5-9,...,80-84, 85+.

I have to do this calculation an awful lot so it would be handy to have this macro ready and waiting but the field with the ages in won't necessarily be the same column all the time.

Can this be done?

RE: Macro to create age bands from an age field

Hi Sarah, thanks for your query. It's a little difficult to create something specific without seeing your source data, but the following code should give you a few pointers on how to achieve the results you want.

First of all, select the cells with the ages in, then run the code. It will loop through the selected cells, categorising them and writing the categories into Column A of Sheet2. I've only put two categories into the code, you will have to complete the rest. It's very rough and ready, and I would probably develop this by switching to using Select Case. I would also customise to your data by writing the categories into the specific column and worksheet you want. Anyway, here is the code:

*****

Sub categorise_me()

Dim curcell As Range
Dim cellcount As Integer
cellcount = 1


For Each curcell In Selection

If curcell.Value > 0 And curcell.Value < 5 Then

Sheets("Sheet2").Range("a1").Cells(cellcount, 1).Value = "0-4"
cellcount = cellcount + 1

End If


If curcell.Value > 5 And curcell.Value < 10 Then

Sheets("Sheet2").Range("a1").Cells(cellcount, 1).Value = "5-10"
cellcount = cellcount + 1

End If



Next curcell

End Sub

*****

Hope this helps,

Anthony

 

Training courses

Training information:

Welcome. Please choose your application (eg. Excel) and then post your question.

Our Microsoft Qualified trainers will then respond within 24 hours (working days).

Frequently Asked Questions
What does 'Resolved' mean?

Any suggestions, questions or comments? Please post in the Improve the forum thread.

Excel tip:

View a unique list

You have a column with hundreds of entries, and you need to see what unique items are entered in it. Select any cell in that column, hold down Alt and press the down arrow: Excel produces an alphabetically-sorted list of unique entries in that column.

View all Excel hints and tips

Connect with us:

0207 987 3777

Call for assistance

Request Callback

We will call you back

Server loaded in 0.12 secs.