dir command vba strange behaviour

C

canvas

Hello,
A question.
I have many directories and files in them. I wrote a vba script to rename
the files in the directories.
The files must have the name of the directory where it's in:
If the file: test.ape is in the directory 12 then the files must be:
12_test.ape.
The script works but the strange thing is that if the filenames are changed
the dir command sees the new
name and renames it again like 12_test12_test_12_test.ape.
Is there a way to avoid this???/

Sub autoopen()
Dim strNewName As String
Dim strOldName As String
Dim pad As String, map As String
Dim test As Integer
Dim x As Integer
pad = ActiveDocument.Path
test = MsgBox("doorgaan?", vbYesNo)
If test = vbNo Then
Exit Sub
End If
For x = 1 To 300
strOldName = Dir(pad & "\" & x & "\*.ape")
Do While Len(strOldName) > 0
strNewName = x & "_" & strOldName
Name pad & "\" & x & "\" & strOldName As pad & "\" & x & "\" &
strNewName
strOldName = Dir()
Loop
Next x
MsgBox "ready"
Application.Quit
End Sub

Thanks a lot
 
J

Jezebel

Dir() retrieves filenames, not files. If you rename the file, that's a new
name, and Dir() retrieves it.

What you need to do is to collect all the filenames in the folder (eg into a
collection), then rename them all, maybe something like this --

Dim pCollection as collection
Dim pName as variant 'Has to be a variant or object to iterate a
collection

For x = 1 To 300

'Get all the names in the folder
set pCollection = new collection
strOldName = Dir(pad & "\" & x & "\*.ape")
Do While Len(strOldName) > 0
pCollection.Add strOldName
strOldName = Dir()
Loop

'Rename the files
For each pName in pCollection
strOldName = pad & "\" & x & "\" & pName
strNewName = pad & "\" & x & "\" & x & "_" & strOldName
Name strOldName As strNewName
Next

Next
 
A

Access101

Is the filename prefix consistent enough to do this:

If mid(fname, 3, 1) = "_" then
'parse before renaming file
else
'rename file normally
end if
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top