使用FSO MoveFile和Name-As重新命名文件不工作

我正在尝试在同一个文件夹中将文件从"X"重命名为"XY" 。 我已经尝试使用文件系统对象,只是名称X作为Yfunction,但都没有工作。 我确实安装了Microsoft Scripting Runtime引用。 代码成功完成,但文件名不变,请指教。

  Dim FSO As Object Dim srcPath As String Dim FromPath As String Dim ToPath As String Dim fldrName As String srcPath = "C:\" i = 1 Set FileSysObj_1 = New FileSystemObject For Each Folder_Obj1 In FileSysObj_1.GetFolder(srcPath).SubFolders i = i + 1 On Error Resume Next Set FSO = CreateObject("scripting.filesystemobject") 'If the file exists in the folder then rename it If Dir(srcPath & Folder_Obj1.Name & "_Hotel.xlsx") Then fldrName = Folder_Obj1.Name FromPath = srcPath & fldrName & "_Hotel.xlsx" ToPath = srcPath & "Hotel.xlsx" '*** Neither of the following two lines work to rename the file FSO.MoveFile FromPath, ToPath Name FromPath As ToPath Else MsgBox "File doesn't exist." End If Next 

你的问题提到你试图重命名同一文件夹中的一个文件,但根据你的代码,你实际上将它移到了C:的根目录。 您可以使用下面的代码来替代上面的代码。 它将重命名文件在其原始文件夹中。

 Dim objFSO As New Scripting.FileSystemObject Dim objFolder As Scripting.Folder For Each objFolder In objFSO.GetFolder("c:\").SubFolders If objFSO.FileExists(objFolder.Path & "\_Hotel.xlsx") Then ' Rename... objFSO.GetFile(objFolder.Path & "\_Hotel.xlsx").Name = "Hotel.xlsx" End If Next 

转到VBA IDE中的工具菜单并select引用。 select“Microsoft脚本运行时”。

然后申报

 Dim FSO As FileSystemObject 

然后MoveFile应该工作。

大警告!

当使用MoveFile重命名一个文件时,它只能使用不带通配符的完整文件名,所以fso.MoveFile(“somepath \ myfile1。*”“somepath \ myfile2”)会在fso.MoveFile(“somepath \ myfile1.pdf”“somepath \ myfile2.pdf“)将工作。 第一个参数中的通配符只有在真正移动到不同的位置而不更改文件名时才有效。 然后第二个参数应以“\”结尾。想知道为什么MSDN上的文档是如此神秘。