98.7% Of all customers recommend us, we're so confident about our results we publish all reviews and stats
View Live Stats View ReviewsForum home » Delegate support and help forum » Microsoft Excel VBA Training and help » Macro to create age bands from an age field | Excel forum
Macro to create age bands from an age field | Excel forum
Resolved · Low Priority · Version 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 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
Any suggestions, questions or comments? Please post in the Improve the forum thread. |
Excel tip:Editing a formula quicklyIf you want to edit a fomrula or text quickly witin a cell instead of the formula bar, you can click either double click in the cell or press the F2 key |