Do Loop for renaming files in folder (1 Viewer)

Wysy

Registered User.
Local time
Today, 14:32
Joined
Jul 5, 2015
Messages
333
Hi,
I have to rename files in a folder in a way that there is an X_ added in front of the name of the file. I have managed it with this code:

Private Sub Command3_Click()
Path = "C:"
file = Dir(Path & "*.csv")
Do While file <> ""
Oldname = file
newname = Path & "X_" & Oldname
Name Path & Oldname As newname
file = Dir
Loop
ReplaceWhat = "X_X_"
ReplaceWith = "X_"
vPath = "C:"
vFile = Dir(vPath & "*.csv")
Do While vFile <> ""
Name vPath & vFile As vPath & Replace(vFile, ReplaceWhat, ReplaceWith)
vFile = Dir
Loop

End Sub

So this works in a way that the first file has the X_ two times and that is why the replacement needs to applied. But is not there any better solution? And why the first loop runs one more extra time for the first file?
thank you
Andrew
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Tomorrow, 05:32
Joined
May 7, 2009
Messages
19,246
it is doing double loop
because once you renamed
the file and saved, it is
again read. since we don't
know which file is being
get by Dir() command, whether
sorted by name, date, etc.

the remedy is to save first all
the files that have been processed
by the Dir command to an Array.
then later rename them all:

Code:
Private Sub Command3_Click()
Dim arrFiles() As String
Dim i As Integer
Path ="C:"
file = Dir(Path & "*.csv")
While file <> ""
	i = i + 1
	Redim Preserve arrFiles(1 To i)
	arrFiles(i) = file
	file = Dir()
Wend
While i <> 0
	Name arrFiles(i) As "X_" & arrfiles(i)
	i = i - 1
Wend
End Sub
d
 

Wysy

Registered User.
Local time
Today, 14:32
Joined
Jul 5, 2015
Messages
333
Thank you so much. I will get it rewritten

Andrew
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Tomorrow, 05:32
Joined
May 7, 2009
Messages
19,246
you should also Exclude those
.csv's that you've already
changed the name (added prefix X_)
before.

Code:
...
...
...
file = Dir(Path & "*.csv")
While file <> ""
	If file Not Like "X_*" Then
		i = i + 1
		Redim Preserve arrFiles(1 To i)
		arrFiles(i) = file
	End If
	file = Dir()
Wend
...
...
...
 

Wysy

Registered User.
Local time
Today, 14:32
Joined
Jul 5, 2015
Messages
333
I have tried it but it does not work. At the name command line it says file is not found.
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Tomorrow, 05:32
Joined
May 7, 2009
Messages
19,246
You add the Path to file:

While I <> 0
Name Path & arrFiles(I) As Path & "X_" & arrFiles(I)
I=i-1
Wend
 

Users who are viewing this thread

Top Bottom