|
-
Dec 9th, 2012, 08:17 PM
#1
New Member
Re: iterating over enum in Excel 2003 VBA macro
Although this is an old thread I thought I should post a solution for the benefit of people Googling this question.
Enums in VBA as in many other languages are just wrappers for Integers, and can be treated as such for a lot of purposes including loops.
So say you have
Code:
Enum Weekday
Monday
Tuesday
'....
Saturday
Sunday
You can loop over all values with a simple for loop:
For day = Monday to Sunday
' Loop code
Next day
Be careful though - if you add a new first or last item to the type such loops will no longer provide complete coverage.
Tested in Excel 2007 but I imagine it will work in all previous versions.
-
Jan 17th, 2013, 06:39 PM
#2
New Member
Re: iterating over enum in Excel 2003 VBA macro
 Originally Posted by Yorgan
Although this is an old thread I thought I should post a solution for the benefit of people Googling this question.
Enums in VBA as in many other languages are just wrappers for Integers, and can be treated as such for a lot of purposes including loops.
So say you have
Code:
Enum Weekday
Monday
Tuesday
'....
Saturday
Sunday
You can loop over all values with a simple for loop:
For day = Monday to Sunday
' Loop code
Next day
Be careful though - if you add a new first or last item to the type such loops will no longer provide complete coverage.
Tested in Excel 2007 but I imagine it will work in all previous versions.
How about if you had code as follows?
Code:
Enum Weekday
Monday=1
Tuesday=3
Wednesday=4
Thursday=5
Friday=6
Saturday=7
Sunday=8
End Enum
Notice the skip over the 2 on the Tuesday Enumeration
Code:
For Day = Monday To Sunday
Debug.Print Day
Next Day
Will return : 1-8 in the immediate window.
Know of any way to test if a number is defined in an enum?
-
May 27th, 2013, 09:36 AM
#3
New Member
Re: iterating over enum in Excel 2003 VBA macro
 Originally Posted by April15Hater
How about if you had code as follows?
Code:
Enum Weekday
Monday=1
Tuesday=3
Wednesday=4
Thursday=5
Friday=6
Saturday=7
Sunday=8
End Enum
Notice the skip over the 2 on the Tuesday Enumeration
Code:
For Day = Monday To Sunday
Debug.Print Day
Next Day
Will return : 1-8 in the immediate window.
Know of any way to test if a number is defined in an enum?
Regarding the first and last items in an Enum, just check the page by the great Chip Pearson
http://www.cpearson.com/excel/Enums.aspx
Simply transcribing, you can define your Enum as
Code:
Enum FruitType
[_First] = 1
Apple = 1
Orange = 2
Plum = 3
[_Last] = 3
End Enum
and later use
or
Unfortunately, some (perhaps all of?) built-in enums apparently do not have those definitions.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|