gpt4 book ai didi

vba - 使用 FSO MoveFile 和 Name-As 重命名文件不起作用

转载 作者:行者123 更新时间:2023-12-04 22:02:38 24 4
gpt4 key购买 nike

我正在尝试从 "X" 重命名文件至"XY"在同一个文件夹中。我曾尝试使用文件系统对象和 Name X as 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

最佳答案

您的问题提到您正在尝试重命名同一文件夹中的文件,但根据您的代码,您实际上是将其移动到 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 - 使用 FSO MoveFile 和 Name-As 重命名文件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31885555/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com