Subfolders collection of FilesystemObject has a count

CharlesChuckieCharles

Well-known Member
Joined
May 10, 2011
Messages
2,153
Subfolders collection of FilesystemObject has a count but you can't reference it?

Subfolders.Count = 12 prefect

Folder.Subfolders(11) not allowed - errors Error 5 Invalid procedure call or argument

likewise

Folder.subfolders.Item(X)

Is the Count of any use other than to tell how many there are?
 
Last edited:

CharlesChuckieCharles

Well-known Member
Joined
May 10, 2011
Messages
2,153
If I have 12 sub folders in a folder

why can't I use


For x = 0 to Subfolders.Count -1

Debug.Print Subfolders(x)

next x

Or

For x = 0 to Subfolders.Count -1

Debug.Print Subfolders.Item(x).Name

next x

etc
 

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
34,389
Office Version
365, 2019, 2016, 2010
Platform
Windows, MacOS
Because the subfolders collection is indexed by name, not number. It's more efficient to iterate using For Each anyway.
 

CharlesChuckieCharles

Well-known Member
Joined
May 10, 2011
Messages
2,153
Thanks Rory for that pointer

I found another explaination ( that if it had been in the HELP or on MSDN would have been enough )

"Cerian Knight ::
Count is already part of the primary layer by design, just type Dir at a command prompt to see the number.
If you read the count and store it, then delete a file, and then re-read the count, it should be different than what you stored.
Your stored value could cause problems in that case.
The same would apply to an index if you stored it for reuse.
Would it point to the same file if you tried to use it? Sure, probably, but for how long?
The problem is that there is no mechanism in the directory structure to pin a file to an index location for any guaranteed amount of time. "


But does that mean the Subfolders collection is updated by processes outside (ie other user updates to a network directory being reflected in my running code)... I think not
 

RoryA

MrExcel MVP, Moderator
Joined
May 2, 2008
Messages
34,389
Office Version
365, 2019, 2016, 2010
Platform
Windows, MacOS
All it really means is that relying on a numeric index is no guarantee that you would get a specific file (much like using Worksheets(1) in Excel). It's not relevant to looping by index number to simply process every file but, as I said, For Each is generally better for that anyway.
 

Forum statistics

Threads
1,082,585
Messages
5,366,466
Members
400,892
Latest member
lamarh755

Some videos you may like

This Week's Hot Topics

Top