【VBA】批量重命名文件夹中的文件(自动数字编号,支持自定义后缀格式)

Sub rename(ByVal path As String, ByVal ext As String)

' 使用方法 call rename("文件夹路径","后缀格式")

' 使用后的效果:例如 00.jpg 01.jpg 02.jpg ......

    Dim MyPath$, MyFile$, NewName$, i&, j&, k&, fileAry() As String, newAry

    MyPath = IIf(Right(path, 1) = "\", path, path & "\")

    MyFile = Dir(MyPath & "*.*")

    i = 1

    Do

        ReDim Preserve fileAry(i - 1)

        fileAry(i - 1) = MyFile

        MyFile = Dir

        i = i + 1

    Loop Until MyFile = ""

    

    newAry = fileAry

    k = Len(CStr(UBound(fileAry)))

    For i = 0 To UBound(fileAry)

        newAry = Filter(newAry, String(k - Len(CStr(i)), "0") & i & ext, False)

    Next i

 

    For i = 0 To UBound(newAry)

        j = 0

        NewName = MyPath & String(k - Len(CStr(j)), "0") & j & ext

        Do Until Len(Dir(NewName)) = 0

            j = j + 1

            NewName = MyPath & String(k - Len(CStr(j)), "0") & j & ext

        Loop

        Name MyPath & newAry(i) As NewName

    Next i

 

End Sub

 

 

' 使用方法 call rename("D:\Documents and Settings\zzllrr\桌面\新建文件夹",".jpg")

posted on 2011-07-28 15:41  zzllrr  阅读(2293)  评论(0编辑  收藏  举报

导航