【问题标题】:excel vba change txt file name (remove time)excel vba更改txt文件名(删除时间)
【发布时间】:2018-06-11 08:23:00
【问题描述】:

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

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

提前谢谢你

迈克

【问题讨论】:

  • 到目前为止你做了什么尝试,你在哪里卡住了?
  • @Storax - 我有一个可以打开 txt 文件但必须手动重命名的宏,我需要一个可以在不打开 txt 文件的情况下更改文件名的宏(如果可能的话)
  • @MichaelMC 是你的原始文件格式总是这样 "ABC_ABCDE_ABCD_YYYYMMDDTTTTTT.txt" ?
  • 你需要 NAME x AS y 命令而不是打开文件
  • @DineshPawar - 是的,格式总是这样,我只需要删除 T(s)。一个将贯穿每个 txt 文件(大约 50+ 个文件)的宏

标签: excel text-files filenames vba


【解决方案1】:

根据我对您问题的理解,我编写了一个代码,要求用户根据需要选择文件夹并重命名“.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

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

【讨论】:

  • @MichaelMC 我很高兴知道您的问题得到了解决,此外,您可以根据需要修改 checkformat 和 newName 变量,也可以通过添加几个来将直接文件夹路径传递给 LoopThroughFiles()代码行数。
猜你喜欢
  • 1970-01-01
  • 2018-11-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多