使用FSO MoveFile和Name-As重命名文件不起作用 [英] Rename file using FSO MoveFile and Name-As not working
问题描述
我正在尝试将同一文件夹中的文件从"X"
重命名为"XY"
.我尝试使用文件系统对象,而仅使用名称X作为Y函数,但是都无法正常工作.我确实安装了Microsoft脚本运行时参考.代码成功完成,但文件名未更改,请告知.
I am trying to rename a file from "X"
to "XY"
in the same folder. I have tried using File System Object and just the Name X as Y function, but neither is working. I do have the Microsoft Scripting Runtime reference installed. The code completes successfully but the file name does not change, Please advise.
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:
.您可以使用以下代码代替上面的代码.它将重命名其原始文件夹中的文件.
Your question mentions that you're trying to rename a file in the same folder but, according to your code, you're actually moving it to the root of C:
. You can use the following code as a replacement for what you have above. It will rename the file in its original folder.
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
这篇关于使用FSO MoveFile和Name-As重命名文件不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!