PDA

View Full Version : Solved: changing to .txt extension



knifelong
10-14-2008, 08:57 AM
The code below is a short piece of code which changes file extensions to .txt. This is a nice piece of code so excuse me not for quoting the person that wrote it as I can't quite remember where I got it. So if its you feel free to own up.
Anyway my problem is that this code simply treats everything after the "." as an extension and changes it to .txt. However I would like to keep the extension after the "." as part of the filename, as these are unique identifiers, but still change the file to .txt.

so for example these files:


patient.a6735
patient.a3823
patient.b5638

would become :

patienta6735.txt
patienta3823.txt
patientb5638.txt

I'm sure its very simple but I'm new to VBA and need a bit of help

Regards.






Sub change_ext()
Dim path1 As String
Dim g As String
Dim filex, object2, object_fso, tempfolder

path1 = "C:\test"
Set object_fso = CreateObject("Scripting.FileSystemObject")
Set tempfolder = object_fso.GetFolder(path1)
Set object2 = tempfolder.Files


For Each filex In object2
g = Left(Dir(filex, vbDirectory), InStr(Dir(filex, vbDirectory), "."))
filex.Name = CStr(g) + "txt"
Next


End Sub

CreganTur
10-14-2008, 09:29 AM
You don't have to remove the existing period. You can just add the .txt onto the end of the filename... or at least you should be able to get away with that and have it work for you. Try this:

Sub change_ext()
Dim path1 As String
Dim g As String
Dim filex, object2, object_fso, tempfolder

path1 = "C:\test"
Set object_fso = CreateObject("Scripting.FileSystemObject")
Set tempfolder = object_fso.GetFolder(path1)
Set object2 = tempfolder.Files

For Each filex In object2
filex.Name = filex.Name & ".txt"
Next
End Sub


See if that does what you want.

Also, don't use the "+" sign for concatenation- it's bad practice. It should only be used for VBA calculations. Using the '&' sign is correct, slightly faster, and standard.