• Excel VBA批量修改文件夹下的文件名


    今天,有同事提出想批量修改文件名,规则比较简单,在第五位后加“-”即可,

    上网没找到相关工具,就自己做了个excel,用宏代码修改。

    代码如下:

    Private Sub CommandButton1_Click()

    Dim varFileList As Variant

    MsgBox "选择要重命名文件所在的文件夹,点击确定!"

    With Application.FileDialog(msoFileDialogFolderPicker)
        .AllowMultiSelect = False
        .Show
       
        If .SelectedItems.Count = 0 Then Exit Sub '未选择文件夹
       
        renamepath = .SelectedItems(1)
       
        If Right(renamepath, 1) <> "" Then
            renamepath = renamepath + ""
        End If
    End With

    '获取文件夹中的所有文件列表
    varFileList = fcnGetFileList(renamepath)

    If Not IsArray(varFileList) Then
        MsgBox "未找到文件", vbInformation
        Exit Sub
    End If

    For l = 0 To UBound(varFileList)
        Dim fs
        Set fs = CreateObject("Scripting.FileSystemObject")
        oName = renamepath & CStr(varFileList(l))
        If fs.FileExists(oName) And Len(CStr(varFileList(l))) > 5 Then
            nName = renamepath & Left(CStr(varFileList(l)), 5) & "-" & Mid(CStr(varFileList(l)), 6)
            Name oName As nName
        End If
    Next l

    MsgBox "全部修改成功!哈哈", vbInformation

    End Sub

    Private Function fcnGetFileList(ByVal strPath As String, Optional strFilter As String) As Variant
    ' 将文件列表放到数组
    Dim f As String
    Dim i As Integer
    Dim FileList() As String

    If strFilter = "" Then strFilter = "*.*"
        Select Case Right(strPath, 1)
        Case "", "/"
        strPath = Left(strPath, Len(strPath) - 1)
    End Select

    ReDim Preserve FileList(0)
    f = Dir(strPath & "" & strFilter)
    Do While Len(f) > 0
        ReDim Preserve FileList(i) As String
        FileList(i) = f
        i = i + 1
        f = Dir()
    Loop
    If FileList(0) <> Empty Then
        fcnGetFileList = FileList
    Else
        fcnGetFileList = False
    End If

    End Function

  • 相关阅读:
    LeetCode–打印从1到最大的n位数
    常用十大算法(十)— 踏棋盘算法
    常用十大算法(九)— 弗洛伊德算法
    常用十大算法(八)— 迪杰斯特拉算法
    LeetCode–组合
    LeetCode–组合总和
    5513. 连接所有点的最小费用 kruskal
    152. 乘积最大子数组 dp
    1567. 乘积为正数的最长子数组长度 dp
    5481. 得到目标数组的最少函数调用次数. 位运算
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3228643.html
Copyright © 2020-2023  润新知