excel 如何不使用(Name)和(FileSystemObject.MoveFile)重命名工作簿?

zqry0prt  于 2023-02-14  发布在  其他
关注(0)|答案(1)|浏览(87)

假设我的桌面上有一个名为Test.xlsm的工作簿,我需要在同一路径中将其重命名为Test2.xlsm
我可以使用Name语句将其重命名为:

Sub Rename_using_Name()
 
    Dim oldName As String, newName As String
 
    oldName = "D:\Users\UserName\Desktop\Test.xlsm"
    newName = "D:\Users\UserName\Desktop\Test2.xlsm"
 
    Name oldName As newName
 
End Sub

或者,我可以使用FileSystemObject进行重命名,如下所示:

Sub Rename_using_FileSystemObject()
 
   Dim fso As Object, oldName As String, newName As String
 
   Set fso = CreateObject("Scripting.FileSystemObject")
 
   oldName = "D:\Users\UserName\Desktop\Test.xlsm"
   newName = "D:\Users\UserName\Desktop\Test2.xlsm"
 
   fso.MoveFile oldName, newName
 
End Sub

我寻求任何额外的手段来重命名工作簿以外的上述引用。
事先,非常感谢您的帮助。

6jjcrrmo

6jjcrrmo1#

你已经有了一些简单的方法来实现你想要的......下面是另一种使用SHFileOperation API的方法

Option Explicit

Private Declare PtrSafe Function SHFileOperation Lib "shell32.dll" _
Alias "SHFileOperationA" (lpFileOp As SHFILEOPSTRUCT) As LongPtr

Private Const FOF_SIMPLEPROGRESS = &H100
Private Const FO_RENAME = &H4

Private Type SHFILEOPSTRUCT
    hWnd As LongPtr
    wFunc As Long
    pFrom As String
    pTo As String
    fFlags As Integer
    fAborted As Boolean
    hNameMaps As LongPtr
    sProgress As String
End Type

Sub Sample()
    SHRenameFile "D:\Users\UserName\Desktop\Test.xlsm", _
                 "D:\Users\UserName\Desktop\Test2.xlsm"
End Sub

Public Sub SHRenameFile(ByVal strSource As String, ByVal strTarget As String)
    Dim op As SHFILEOPSTRUCT

    With op
        .wFunc = FO_RENAME
        .pTo = strTarget
        .pFrom = strSource
        .fFlags = FOF_SIMPLEPROGRESS
    End With

    '~~> Perform operation
    SHFileOperation op
End Sub

相关问题