我正在尝试将文件从"X"
重命名为同一文件夹中的"XY"
。我已经尝试使用文件系统对象和名称X作为Y函数,但两者都没有工作。我确实安装了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
答案 0 :(得分:2)
您的问题提到您正在尝试重命名同一文件夹中的文件,但根据您的代码,您实际上是将其移至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
答案 1 :(得分:1)
转到VBA IDE中的工具菜单,然后选择引用。选择" Microsoft Scripting Runtime"。
然后宣布
NULL
然后MoveFile应该可以工作。