我正在分析一个文件结构,它涉及到使用Folder对象的.Subfolders集合。然而,一旦代码到达我使用集合的第一个实例,子将停止执行代码并退出。没有显示错误。以下相关代码:
首先,在另一个子系统中,有问题的子系统被称为:
Option Explicit
Public folderlevel As Integer
Private Sub exportButton_Clicked
Dim fso As Object, startFolder As Object, Path As String, intFileDesc As Integer
'This will summon a file browser window to allow user to navigate comfortably to the folder where the output file should be saved
With Application.FileDialog(msoFileDialogFolderPicker)
.Title = "Please choose the folder where you'd like to save this record"
.Show
End With
'Save the selected folder as a string that contains a path (with a backslash at the end for proper syntaxis)
Path = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) & ""
Set fso = CreateObject("Scripting.FileSystemObject")
Set startFolder = fso.getFolder(Path)
intFileDesc = FreeFile
folderLevel = 0
getContents startFolder, intFileDesc
Debug.Print "Output Finished"
End Sub
然后实际子的代码:
Sub getContents(ByRef prntfldr As Object, targetFile As Integer)
Dim SubFolder As Object, File As Object, SFCollection
folderLevel = folderLevel + 1
Debug.Print "getContents entered, starting analysis from " & prntfldr.Name
Set SFCollection = prntfldr.Subfolders
Debug.Print "Entering first subfolder"
For Each SFolder In SFCollection
Print #targetFile, "|"; String((50 * (folderLevel - 1)) - 1, " "); "|"; String(49, "-"); SFolder.Name
Debug.Print "Level " & folderLevel & ", Working in folder " & SFolder.prntfldr.Name & ", printing contents of" & SFolder.Name
getContents SFolder, targetFile
Next SFolder
folderLevel = folderLevel - 1
End Sub
添加了";设置";到SFCollection行,这将使我进入For Each循环,但没有任何内容被打印到文件或立即窗口。
最奇怪的是,这段代码在Excel中运行得非常好。
此修改不会出错,并输出到即时窗口:
For Each SubFolder In SFCollection
Debug.Print "Level " & folderlevel & ", Working in folder " & _
prntfldr.Name & ", printing contents of " & SubFolder.Name
getContents SubFolder, targetFile
Next SubFolder
可能会对此感兴趣http://allenbrowne.com/ser-59.html