You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用For Each遍历Folder文件时重命名导致文件被重复处理的问题

遍历FileSystemObject文件集合时的重命名重复处理问题

我一直采用一种编码实践:借助Windows Scripting Runtime的FileSystemObject遍历文件夹中的每个文件并执行相应操作,代码示例如下:

Public Function RestoreOriginalPicNames(pFolderPath As String, pCharsToChop As Byte) As Boolean

Dim objFSO As New FileSystemObject
Dim objFolder As Folder
Dim objFile As File
Dim FileName As String
Dim FileNameNoExt As String
Dim FileNewName As String

Dim FileExt As String

Set objFolder = objFSO.GetFolder(pFolderPath)
For Each objFile In objFolder.Files
    FileName = objFile.Name
    FileExt = GetExtFromFileName(FileName)
    FileNameNoExt = Left$(FileName, Len(FileName) - Len(FileExt) - 1)
    If FileExt = "JPG" Then
        If Len(FileName) > pCharsToChop Then
            FileNewName = Right$(FileName, Len(FileName) - pCharsToChop)
            objFile.Name = FileNewName
            Debug.Print FileNewName
        End If
    End If
    
Next objFile

RestoreOriginalPicNames = True

End Function

此次首次出现异常:文件集合似乎在循环中途从文件系统自动刷新,导致两个文件(可能与原名称/重命名后的名称特性相关)被重复处理两次。

我原本认为执行For Each File In [Folder]语句时,会从文件系统内部填充静态数组,即循环期间对文件夹内容的后续变更会被忽略。但本次案例中,两个文件被重命名后,又被For Each循环再次捕获,进而被处理两次。

可行的解决方案是先显式填充文件名数组,再遍历该数组处理文件(初始数组填充完成后不再访问文件系统)。

我担心这种原有的编码实践并非绝对可靠,因为我在多处代码中都使用了该写法。


内容的提问来源于stack exchange,提问作者SebTHU

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 06:04:59