user1379351
user1379351

Reputation: 785

Is it possible to iterate over a FileSystemObject SubFolders collection by index?

I understand that it's possible to iterate over SubFolders using a For Each loop, as follows:

for each f in myfolder.SubFolders
    WScript.Echo f.ShortName
next

However, I would like to iterate by index. I can't seem to get it to work, nor find any examples online. This is what I have tried:

for i = 1 to myfolder.SubFolders.Count
    WScript.Echo myfolder.SubFolders.Item(i).ShortName
next

Any suggestions?

EDIT

Here is the use case:

For at least one of my subfolders, I get a Permission Denied error which happens on the for each line. As such I need to wrap the whole for loop in error handling:

on error resume next
for each f in folderobj.SubFolders
    ' do some stuff
next
on error goto 0

What I want to do is finer grained more controlled error handling, like this:

for i = 0 to folderobj.SubFolders.Count - 1
    on error resume next
    ' access folder
    if Err.Number = RELEVANT_ERROR_NUMBER then
        ' do something sensible
    end if
next

Upvotes: 1

Views: 503

Answers (1)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200293

As @Lankymart already pointed out the Folders collection returned by the SubFolders property doesn't allow access by index, only by name. If you need indexed access you will have to put the folder objects into an array first:

ReDim sf(myfolder.SubFolders.Count - 1)
i = 0
For Each f In myfolder.SubFolders
  Set sf(i) = f
  i = i + 1
Next

Then you can access the elements in sf by index.

For i = 0 To UBound(sf)
  WScript.Echo sf(i).ShortName
Next

Note that VBScript arrays are zero-based, so the index will run from 0 to .SubFolders.Count-1.

Note also that if anything changes the collection you must re-synchronize the array with the collection yourself. It won't pick up changes automagically.

Upvotes: 2

Related Questions