excel vba 更改txt文件名(删除时间)

excel vba change txt file name (remove time)

如何使用 excel vba 以编程方式更改 .txt 的文件名,我需要一个脚本,它会遍历包含 txt 文件的文件夹并从中删除时间文件名.

原始文件名:ABC_ABCDE_ABCD_YYYYMMDDTTTTTT.txt 新文件名:ABC_ABCDE_ABCD_YYYYMMDD.txt

提前致谢

麦克

根据我对您问题的理解,我编写了一段代码,要求用户 select 文件夹并根据要求重命名“.txt”文件,您可以添加额外的代码行完美的作品

'call sub LoopThroughFiles   
'this sub is loop every file and rename it
Sub LoopThroughFiles()

    Dim txtfile As String, folderPath As String
    Dim newName As String

    folderPath = GetFolder()
    txtfile = Dir(folderPath & "\" & "*.txt")

    While txtfile <> ""

          If checkFormat(txtfile) = True Then
             newName = Left(txtfile, 23) & ".txt"
           On Error Resume Next
           'rename file is done here
    If Not txtfile = "" Then Name (folderPath + "\" + txtfile) As (folderPath + "\" + newName)
            On Error GoTo 0

         End If
        txtfile = Dir

    Wend
End Sub

'this function is for check format of file
'you may edit it as per your requirment
Function checkFormat(str As String) As Boolean
checkFormat = False
If Len(str) = 33 And Mid(str, 4, 1) = "_" Then
    checkFormat = True
End If

End Function

'this function for select folder path
Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

在使用此代码之前,请为您的文件制作一份额外的副本,以防万一出现错误您有一个备份... 希望这有帮助