Excel VBA Change Text Filename (remove time)

michaelmc

New Member
Joined
Nov 23, 2014
Messages
4
Hi Guys,

How do I programmatically change the file name of a txt file using excel vba, I need a script where it will go through a folder which consists of txt files and change the txt filename by removing Time.

Original Filename: ABC_ABCDE_ABCD_YYYYMMDDTTTTTT.txt
New Filename: ABC_ABCDE_ABCD_YYYYMMDD.txt

Thank you in advance

Mike
 

Excel Facts

Remove leading & trailing spaces
Save as CSV to remove all leading and trailing spaces. It is faster than using TRIM().
found the solution, posting it here for the benefit of other users

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
 
Upvote 0

Forum statistics

Threads
1,215,025
Messages
6,122,732
Members
449,093
Latest member
Mnur

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top