Trouble removing/changing csv filenames via vba

DRANDON

Active Member
Joined
Jun 30, 2006
Messages
268
Hello all. I have code that I've put together in an effort to remove a section of the filename in a series of csv files in a folder. Example "fhw_cpa_denial_report_20180802.csv" and "hmmc_cpa_denial_report_20180802.csv". They all vary in length but all I need to remove is anything after the underscore (essentially the underscore and the date).

Here is what I have:

Sub CleanFilenames()
Dim LastDot As Long, ThePath As String, OldFilename As String, NewFilename As String
ThePath = "C:\Users\ldc580\Desktop\New folder"
OldFilename = Dir(ThePath & "*.csv")

Do While Len(OldFilename)
NewFilename = Application.Remove(OldFilename, Len(OldFilename) - 13, 0, "")
Name Path & OldFilename As Path & NewFilename
OldFilename = Dir()
Loop
End Sub

It does not work. Any help would be greatly appreciated as it will automate a process that takes to long. Thank you in advance..
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
How about
Code:
NewFilename = Left(OldFilename, InStrRev(OldFilename, "_") - 1)
Name ThePath & OldFilename As ThePath & NewFilename & ".csv"
This assumes that you want to keep the file extension
 
Upvote 0
I had to change this "C:\Users\ldc580\Desktop\New folder" to this "C:\Users\ldc580\Desktop\New folder" and implemented your suggestion and it worked instantly! Fantastic! Many many thanks
 
Upvote 0
Glad to help & thanks for the feedback
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,184
Members
453,020
Latest member
Mohamed Magdi Tawfiq Emam

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