我有一个VBA函数,它创建一个FileSystemObject实例,并使用它来读取目录的内容并根据条件逻辑执行一些操作。
在函数中,我使用一个循环来读取目录的内容。 我的问题是:在循环打开之后但在关闭之前将新文件添加到目录时会发生什么??操作系统是否知道将此文件包含在文件集合中?或者是打开循环时对dir采取的“快照”,导致新添加的文件被忽略?
请纠正我上面可能使用的任何不正确的术语。
我的代码如下:
Function fn_FileCheckType()
'load INI data
fn_ReadINI
'does filename end with .xls or .xlsx?
'read files from iDumpFolder
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
Dim objFolder As Object
Set objFolder = fs.GetFolder(iDumpFolder)
Dim objFile As Object
For Each objFile In objFolder.files
If (objFile.Name Like "*.xls" Or objFile.Name Like "*.xlsx") Then
'do nothing
Debug.Print objFile.Name & " is valid."
Else
'copy to invalid file archive and delete from inbox
objFile.Copy (iInvalidArchive & "\" & objFile.Name)
MsgBox (objFile.Name & " is not saved as .xls or .xlsx. Please modify and re-import.")
objFile.Delete
End If
Next 'objFile
'Cleanup
Set objFolder = Nothing
Set objFile = Nothing
Set fs = Nothing
End Function
答案 0 :(得分:2)
以下VBA代码表示.Files
集合是引用集合时文件夹中文件的“快照”。在运行代码之前,我在测试文件夹中放置了两个文件:b.txt
和c.txt
。 Debug.Assert
语句在第一次进入循环后立即挂起代码。在暂停时,我添加了文件a.txt
和d.txt
,然后点击 F5 以继续执行。该代码仅列出最初位于该文件夹中的两个文件。
Option Compare Database
Option Explicit
Public Sub FilesCollectionTest()
Dim fso As New FileSystemObject, objFolder As Folder, objFile As File, i As Long
Set objFolder = fso.GetFolder("C:\__tmp\zzzTest")
i = 1
For Each objFile In objFolder.Files
Debug.Assert i > 1
Debug.Print objFile.Name
i = i + 1
Next
Set objFile = Nothing
Set objFolder = Nothing
Set fso = Nothing
End Sub
答案 1 :(得分:1)
每次迭代都会重新评估您编写示例objFolder.files
的方式,从而获得任何更改。但是,如果你像
Dim fso As New FileSystemObject
Dim files, f
Set files = fso.GetFolder("C:\~\My test Folder").files
For Each f In files
debug.print f.name
Next f
Debug.Print ' break point here
Debug.Print
即使您不在循环Files
中,也会刷新。我在循环之后在第一个Print
上放置一个断点,将一个文件添加到我的文件夹然后点击 F8 ,并将Files
更新为正确的文件计数。