作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试从 "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/
我是一名优秀的程序员,十分优秀!