将多个文件夹中的旧名称重命名为VBA中的新名称

时间:2017-02-27 09:23:09

标签: excel vba excel-vba

我第一次在Microsoft Excel中使用VBA。我必须将不同文件夹中的旧名称更改为新名称。

OldName     path                    NewName     
Dayz.xls    C:\Users\Staffs\Dayz\   DayzStaff.xls
Mary.xls    C:\Users\Staffs\Mary\   MaryStaff.xls

最多100条记录

我试过下面的代码。但是如何在VBA中循环?请帮我解决这个问题。

oldfilename = "C:\Users\Staffs\Dayz\Dayz.xls"
newfilename = "C:\Users\Staffs\Dayz\DayzStaff.xls"
Name oldfilename As newfilename

2 个答案:

答案 0 :(得分:1)

这样就可以了。它将从Staffs文件夹中获取所有Excel文件名,并将Staff附加到名称的末尾。这将采取任何扩展名为' xls'。

Public Sub RenameFiles()

    Dim vFiles As Variant
    Dim vFile As Variant

    'Get all file names of XLS files from C:\Users\Staffs & subfolders.
    vFiles = EnumerateFiles("C:\Users\Staffs\", "xls*")

    'Cycle through each name.
    For Each vFile In vFiles
        'Take everything to the left of the last . add "staff" and add the extension back on.
        'If they're all the same file type (xls or xlsx) then you can remove the
        'MID command and just type use xls.
        Name vFile As Left(vFile, InStrRev(vFile, ".") - 1) & " Staff" & Mid(vFile, InStrRev(vFile, "."))
    Next vFile

End Sub

Public Function EnumerateFiles(sDirectory As String, _
            Optional sFileSpec As String = "*", _
            Optional InclSubFolders As Boolean = True) As Variant

    EnumerateFiles = Filter(Split(CreateObject("WScript.Shell").Exec _
        ("CMD /C DIR """ & sDirectory & "*." & sFileSpec & """ " & _
        IIf(InclSubFolders, "/S ", "") & "/B /A:-D").StdOut.ReadAll, vbCrLf), ".")

End Function

答案 1 :(得分:1)

如果工作表上已有一个范围,其中包含文件夹列表,并且XLSX被命名为文件夹(根据上面的示例),那么这就可以了:

rootfldr = "C:\Users\Staffs\"
For Each fldrname In Sheets("sheet1").Range("A1:A100").Value ' the range of the list
    oldfilename = rootfldr & fldrname & "\" & fldrname & ".xlsx"
    newfilename rootfldr & fldrname & "\" & fldrname & "Staff.xlsx"
    Name oldfilename As newfilename
Next