VBA更改文件夹中所有文件的名称

时间:2019-03-10 10:13:36

标签: vba

在一个文件夹中,我有一些名为1; 2; 3; 4; 5; 6的图像,我需要像这样更改每个图像的名称:

1变成6 / 2变成5 / 3变成4 ...等等

此示例可处理6张图像,但我可以拥有更多图像。

我开始进行一些遍历目录中所有文件的工作

Sub LoopThroughFiles()
Dim StrFile As String
StrFile = Dir("c:\xxx\*test*")
Do While Len(StrFile) > 0
    Debug.Print StrFile
    StrFile = Dir
Loop
End Sub

我可能需要将它们复制到另一个文件夹中,因为如果已有一个文件,我无法命名文件6?

感谢您的帮助

2 个答案:

答案 0 :(得分:1)

如果“ 6”仍然存在,则无法将文件“ 1”重命名为“ 6”,因此我们需要首先将每个文件重命名为临时名称。因此,我们将文件夹中的所有文件循环两次。请注意,文件必须仅命名为数字(加扩展名),否则代码将失败。在运行脚本之前备份图像。

Public Sub rename_all_files_in_folder(folderPath As String)

'''   for this code to work, Microsoft Scripting Runtime reference is required (Tools -> References)
Const temp_filename_prefix As String = "to_be_renamed_"
Dim fso As Scripting.FileSystemObject
Dim f As Scripting.file
Dim fileCount As Integer
Dim newFilename As String
Dim extension As String

Set fso = New FileSystemObject

fileCount = 0
If fso.FolderExists(folderPath) Then

    '''   first cycle, each file gets temporary name
    For Each f In fso.GetFolder(folderPath).Files
        fileCount = fileCount + 1
        'fso.FindFileInFolder = f.Name
        f.Name = temp_filename_prefix & f.Name
    Next f

    '''   second cycle to rename from temporary name to new name
    For Each f In fso.GetFolder(folderPath).Files
        extension = "." & fso.GetExtensionName(f.path)
        newFilename = CStr(fileCount + 1 - CInt(Replace(Replace(f.Name, temp_filename_prefix, ""), extension, ""))) & extension
        f.Name = newFilename
    Next f
Else
    MsgBox "Folder not found:" & vbCrLf & folderPath
End If
End Sub

答案 1 :(得分:1)

您可以使用:

Public Sub SwapFiles()
    Dim folderPath As String
    Dim fileCount As Long

    folderPath = "c:\xxx" ' folder path to search files into

    With CreateObject("Scripting.FileSystemObject")
        For fileCount = 1 To 3
            .CopyFile folderPath & "\" & fileCount & ".jpg", folderPath & "\" & "temp.jpg"
            .CopyFile folderPath & "\" & (6 - fileCount + 1) & ".jpg", folderPath & "\" & fileCount & ".jpg"
            .CopyFile folderPath & "\" & "temp.jpg", folderPath & "\" & (6 - fileCount + 1) & ".jpg"
        Next
    End With
End Sub

只需将“ jpg”更改为实际的图像文件扩展名