使用vba将文件从一个文件夹复制到另一个文件夹

关于这个话题有一些类似的post,我知道。 但是,我有一个代码,这个代码与我在这里看到的所有代码都不一样(当谈论这个主题的时候)。

我收到的错误是说,该文件找不到。 但是这是不可能的,因为我在fso.CopyFile中使用SOURCE的文件夹中search文件。

所以我必须解决这个错误,如果可能的话,我想将文件复制到另一个文件夹并更改名称。 例如,如果我有文件“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 

这是因为fso.CopyFile "C:\Users\Desktop\Files\file", "C:\Users\Desktop\Files\Old\file"不是一个文件…这只是一个string从一个虚拟文件它的外观。

如果相反,线路是

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

更新后添加:

我只是试图使用(subbing计算机的用户名下面),并成功地将所有内容移动到一个新的文件夹:

 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来获取我的桌面,然后把它扔到我在桌面上创build的新文件夹(在运行脚本之前)名为“test”。

要移动文件夹中的所有文件:

 Sub MoveFiles() Dim MyFile As String MyFile = Dir("C:\AAAA\*.*") Do Until MyFile = "" Name "C:\AAAA\" & MyFile As "C:\AAA\" & MyFile MyFile = Dir Loop End Sub