Warm tip: This article is reproduced from serverfault.com, please click

excel-使用VBA将文件从一个文件夹复制到另一个文件夹

(excel - Copying files from one folder to another using vba)

发布于 2014-10-07 17:40:20

我知道有一些与此主题相关的类似文章。但是,我的代码不同于我在这里看到的所有代码(谈论此主题时)。

我收到的错误是说找不到该文件。但这是不可能的,因为我正在fso.CopyFile中作为源使用的同一文件夹中搜索文件。

因此,我必须修复此错误,如果可能的话,我想将文件复制到另一个文件夹并更改名称。例如,如果我有文件“ Excel.xls”,我想使用名称“ Excel_old.xls”进行复制,是否可以使用下面的代码,或者是否太不值得?

这是代码:

Sub CopyFiles()
'Macro to copy all files modified yesterday

Dim n As String, msg As String, d As Date
Dim fso As Object

Set fso = CreateObject("Scripting.FileSystemObject")
Set fils = fso.GetFolder("C:\Users\Desktop\Files\").Files

'Verify all files in the folder, check the modification date and then copy 
'to another folder (named Old)
For Each fil In fils
    n = fil.Name
    d = fil.DateLastModified
    If d >= Date - 1 Then
        file = n
        'The following line is where the error occurs
        fso.CopyFile "C:\Users\Desktop\Files\file", "C:\Users\Desktop\Files\Old\file"

    End If
Next fil

End Sub
Questioner
dekio
Viewed
0
JNevill 2014-10-08 03:40:54

这是因为fso.CopyFile "C:\Users\Desktop\Files\file", "C:\Users\Desktop\Files\Old\file"不是文件...从外观上来说,这只是一个虚拟文件的字符串。

如果相反,那条线是

fso.CopyFile fil.Path, "C:\Users\Desktop\Files\Old\" & fil.name...可能会起作用。

更新后添加:

我只是尝试使用以下命令(将计算机用户名放在下面),并且成功将所有内容移动到新文件夹中:

Sub test()
    Dim fso As FileSystemObject
    Dim fsoFiles As Files
    Dim fil As File

    Set fso = New FileSystemObject
    Set fils = fso.GetFolder("C:\Users\<MY USERNAME>\Desktop\").Files

    For Each fil In fils
        n = fil.Name
        d = fil.DateLastModified
        fso.CopyFile fil.Path, fil.ParentFolder & "\test\" & fil.Name

    Next fil
End Sub

唯一的区别是,我使用fil.ParentFolder来获取我的桌面,然后将其扔到我在桌面上创建的新文件夹中(运行脚本之前),名为“ test”。