使用Excel VBA重命名文件夹中的子文件夹

时间:2019-07-04 08:17:43

标签: excel vba

我正在尝试重命名特定文件夹(C:Users \ admin \ Documents \ AWS)中的所有子文件夹。在A列中,我有旧的文件夹名称,将其更改为B中的相应新名称。

这是我尝试的代码(在Visual Basic编辑器的Sheet17中键入)。 Sheet17是工作簿中的电子表格,带有两列文本。所有子文件夹都在AWS文件夹中。

Sub rename_folder()
    Const FILEPATH As String = "C:Users\admin\Documents\AWS\"
    Dim strfile As String
    Dim filenum As String
    strfile = Dir(FILEPATH)

    Dim old_name, new_name As String

    For i = 2 To Sheets(17).Range("a1").End(xlDown).Row
        strOldDirName = FILEPATH & Sheets(17).Cells(i, 1).Value
        strNewDirName = FILEPATH & Sheets(17).Cells(i, 2).Value
        Name strOldDirName As strNewDirName
    Next i

    MsgBox "Congratulations! You have successfully renamed all the Folders"
End Sub

我知道了

  

运行时错误'53':找不到文件

在运行代码时。找不到调试窗口(我在Mac上,使用Microsoft 2017),但是它可能是前几行代码之一。请让我知道以后的任何一行是否也应更改。

2 个答案:

答案 0 :(得分:0)

可能是

Const FILEPATH As String = "C:\Users\admin\Documents\AWS\"

代替

Const FILEPATH As String = "C:Users\admin\Documents\AWS\"

驱动器号后缺少\的原因

答案 1 :(得分:0)

这对我来说很好。

Sub rename_folder()
Const FILEPATH As String = "C:\Users\Excel\Desktop\test\"
Dim strfile As String
Dim filenum As String
strfile = Dir(FILEPATH)

Dim old_name, new_name As String
For i = 2 To Sheets(1).Range("a2").End(xlDown).Row
    strOldDirName = FILEPATH & Sheets(1).Cells(i, 1).Value
    strNewDirName = FILEPATH & Sheets(1).Cells(i, 2).Value
    Name strOldDirName As strNewDirName
Next i
MsgBox "Congratulations! You have successfully renamed all the Folders"
End Sub

之前:

enter image description here

之后:

enter image description here