首页 > 解决方案 > 使用 VBA 重命名文件夹

问题描述

我正在尝试根据用户将填写的模板重命名文件夹。用户将指定文件夹的旧名称以及将要更新的内容。有一堆子文件夹也会更改名称。

我已经确认这些文件夹存在并且在它们应该存在的位置,所以我不明白为什么会失败。我也尝试过使用 FileSystem 对象并遇到同样的问题。

任何帮助将不胜感激。

Sub UpdateMain()

    'string capture variables
    Dim currentLocation As String
    Dim currentName As String
    Dim customerNumber As String
    Dim newName As String

    'path creation variables
    Dim rootPath As String
    Dim currentPath As String
    Dim newPath As String

    'counter variables
    Dim i As Integer

    With wsUpdate
        currentLocation = .Range("B1")
        currentName = .Range("B2")
        customerNumber = .Range("B3")
        newName = .Range("B5")
    End With

    'create path and folder for the root folder
    rootPath = currentLocation & "\" & currentName & " (" & customerNumber & ")"

    'edit all subfolders prior to root folder
    i = 0
    With wsUpdate.Range("A8")
        Do Until .Offset(i, 0) = ""
                If .Offset(i, 1) = "Customer" Then
                    currentPath = rootPath & "\" & currentName & " " & .Offset(i, 0)
                    newPath = rootPath & "\" & newName & " " & .Offset(i, 0)
                Else
                    currentPath = rootPath & "\" & currentName & " " & .Offset(i, 1) & "\" & currentName & " " & .Offset(i, 0)
                    newPath = rootPath & "\" & newName & " " & .Offset(i, 1) & "\" & newName & " " & .Offset(i, 0)
                End If
                Call FolderNameEdit(currentPath, newPath)
            i = i + 1
        Loop
    End With

    'edit root folder
    currentPath = currentLocation & "\" & currentName & " (" & customerNumber & ")"
    newPath = currentLocation & "\" & newName & " (" & customerNumber & ")"
    Call FolderNameEdit(currentPath, newPath)

End Sub

Sub FolderNameEdit(currentPath As String, newPath As String)
    Name currentPath As newPath
End Sub

我不断得到

运行时错误“53”:找不到文件。

在线发生错误:

Name currentPath as newPath

标签: vba

解决方案


重命名前检查文件夹:

Sub FolderNameEdit(currentPath As String, newPath As String)
    If Dir(currentPath, vbDirectory) = vbNullString Then
        ' error
    ElseIf Dir(newPath, vbDirectory) <> vbNullString Then
        ' error
    Else
        Name currentPath As newPath
    End If
End Sub

推荐阅读