如何使用excel vba以编程方式更改.txt的文件名,我需要一个脚本,它将通过一个包含txt文件的文件夹并从文件名中删除时间。
原始文件名:ABC_ABCDE_ABCD_YYYYMMDDTTTTTT.txt 新文件名:ABC_ABCDE_ABCD_YYYYMMDD.txt
提前谢谢
麦克
答案 0 :(得分:0)
根据我对您的问题的理解,我编写了一个代码,要求用户选择文件夹并根据要求重命名“.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
在使用此代码之前,请为您的文件另外制作一份副本,以防有一些错误,您有备份... 希望这个帮助