Monday 15 July 2013

foreach - How to have for each loop in vba skip to next iteration? -


I've got a file reader from excelexperts.com which lists the files in a folder (and the option to include subfolders I have) "Thunds DB." Decided to tweak the code to leave the files.

I got a code working with the Goto statement, but I know that it is considered bad programming and what was thinking would be the proper code. ) Set MyObject = New Scripting.FileSystemObject set to mySource = MyObject.GetFolder (mySourcePath) Error Resume on every MyFile for mySource.Files ** If myFile.Name = "Thumbs.db" then GoTo nextone Else ** ICol = 2 Cells (IRow, iCol). Value = myFile.Path iCol = iCol + 1 cell (iRow, iCol) .Value = myFile.Name iCol = iCol + 1 cell (iRow, iCol) .Value = myFile.Size iCol = iCol + 1 cell (iRow, iCol) . Value = myFile.DateLastModified iRow = iRow + 1 ** End if ** ** Next: ** Next if the MySources.SubFolders call list for each MySubFolders is MyFiles (mySubFolder.Path, true) end then ending sub

The parts I added were explained in double stars.

In my last attempt, I had added the following code:

  if myFile.Name = "Thumbs.db" followed by the next code remaining code here   

But I got the error "Next without error" which is why I went with the Goto statement that I am hoping to change something better.

Just change if you have the argument of the statement around it:

  MyFile.Name for every myFile in mySource.Files & lt; & Gt; "Thumps DB" then Icalls = 2 cells (IRO, Icalls). Value = MyFile.Path ICol = iCol + 1 cell (iRow, iCol). Value = MyFile .name iCol = iCol + 1 cell (iRow, iCol). Value = myFile.Size iCol = iCol + 1 cell (iRow, iCol). Valu = myFile.DateLastModified iRow = iRow + 1 end if the next   

If you are going to make additional arguments on how to leave files in the future, then you have different reasoning logic Should move.

  for each myFile in MySource.Files if ShouldProcessFile (myFile) then iCol = 2 Room (iRow, iCol)). Values ​​= myFile.Path iCol = iCol + 1 cells (iRow, iCol) .Value = myFile.Name iCol = iCol + 1 cell (iRow, iCol) .Value = myFile.Size iCol = iCol + 1 cells (iRow, ICol) .Value = myFile.DateLastModified iRow = iRow + 1 End if Next Function ShouldProcessFile (File) ShouldProcessFile = True if file.Name = "Thumbs.db" then ShouldProcessFile = False End Function    

No comments:

Post a Comment