【问题标题】:Rename a file with FileSystemObject while looping through files在循环文件时使用 FileSystemObject 重命名文件
【发布时间】:2013-08-10 09:49:28
【问题描述】:

作为前言,我在 Access 2003 中编写代码,但会有用户使用 Access 2013,因此我需要它兼容两者。我有一个循环,它使用 Application.FileSearch 循环浏览目录中的许多文件。据我了解,这在较新版本的 Access 中已被弃用,因此我必须使用“For Each”来循环文件。

这是我要更改的代码:

strPath = CurrentProject.Path & "\Files\"

strFileName = "SourceCode.txt"

With Application.FileSearch
    .FileName = "*.txt"
    .LookIn = strPath
    .Execute
    intFileCount = .foundfiles.Count
    For x = 1 To intFileCount
        Set fs = CreateObject("Scripting.FileSystemObject")
        Set f = fs.GetFile(.foundfiles(x))
        strNewFileName = Right((.foundfiles(x)), Len((.foundfiles(x))) - (InStr((.foundfiles(x)), "Files\") + 5))
        fs.MoveFile f, strPath & strFileName
        'Run the Process() function
        Process
        FileCopy strPath & strFileName, strPath & "Processed\" & strNewFileName
        Kill strPath & strFileName
    Next x
End With

这是我要替换的代码:

strPath = CurrentProject.Path & "\Files\"

strFileName = "SourceCode.txt"

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(strPath)
Set fc = f.Files

For Each f1 In fc
    Set objFSO = CreateObject("Scripting.FileSystemObject")
    Set objFile = objFSO.OpenTextFile(strPath & f1.Name, 1)
    strNewFileName = f1.Name
    f1.Name = strFileName
    'Run the Process() function
    Process
    FileCopy strPath & strFileName, strPath & "Processed\" & strNewFileName
    Kill strPath & strFileName
Next

这段代码循环遍历每个文件,然后启动一个 Process() 函数来更改文件。所以我让它工作的方式是将活动文件更改为“SourceCode.txt”,然后 Process() 函数知道使用该名称的文件。然后它将文件移动到“已处理”子文件夹,并使用其原始文件名。

这在原始代码中运行良好。新代码似乎大部分都可以工作,除了在启动 Process() 之前我找不到将文件重命名为“SourceCode.txt”的方法。我尝试了几种方法,但我不断收到错误。在上面的代码中,我尝试了“f1.Name = strFileName”。这给了我一个“权限被拒绝”错误。我尝试交替使用 FileCopy,然后对原始文件使用 Kill 命令,但 Kill 命令返回错误。我怀疑 FileSystemObject 正在锁定文件,因此无法移动或杀死它。但是旧版本的代码可以毫无问题地移动它。

【问题讨论】:

    标签: ms-access vba ms-access-2003 ms-access-2013


    【解决方案1】:

    您收到“权限被拒绝”,因为您试图在文件使用时重命名文件,即objFSO.OpenTextFile。这与 fs.GetFile 不同,并且不在您的原始代码中 - 您需要它吗?它返回一个您随后不使用的TextStream

    无论如何,请在打开文件之前将f1.Name = strFileName 移动到,或者在完成处理后,调用objFile.Close 然后重命名。

    【讨论】:

    • 你说得对。我不需要在这个函数中打开文件。我想我在某处抓取了示例代码来模拟“For Each”循环,而那部分就在其中。删除它解决了这个问题。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-04
    • 1970-01-01
    • 2019-07-05
    • 2019-06-27
    • 2012-02-12
    • 1970-01-01
    相关资源
    最近更新 更多