Macro to rename files

D

Diana Morrison

I have 4 folders - in each there are 400 documents with 2 letters in the
middle of each file name, i.e. 12345 AE weekly. I used Steven's suggestion
posted in Microsoft VBA General questions dated 6/29/2007 "replace text
string in Word Automatically" to find and replace words within those
documents - can I use similar code (where you choose the directory) to change
the file names, i.e. find "AE", replace with "MA" in the file name.
Thanks,
Diana
 
D

Diana Morrison

Gotta give credit where credit is due - I meant Graham Mayor's code, not
Steven's. :)
 
D

Doug Robbins - Word MVP

The following code will replace AE in the filename with MA:

Dim myName As String
Dim myPath As String
Dim myDoc As Document
With Dialogs(wdDialogCopyFile)
If .Display() <> -1 Then Exit Sub
myPath = .Directory
End With
If Len(myPath) = 0 Then Exit Sub
If Asc(myPath) = 34 Then
myPath = Mid$(myPath, 2, Len(myPath) - 2)
End If
myName = Dir$(myPath & "*.*")
Do While myName <> ""
Set myDoc = Documents.Open(myPath & myName)
myDoc.SaveAs myPath & Replace(myName, "AE", "MA")
myDoc.Close
Kill myPath & myName
myName = Dir
Loop

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
D

Diana Morrison

Thanks Doug. I tried this but get a compile error: wrong number of
arguments or invalid property assignment. Appreciate your help. --Diana
 
D

Doug Robbins - Word MVP

What version of Word are you using? If you press Debug when you get the
error message, which line of the code is highlighted?

I suspect that it is the Replace() function that may be causing the error,
definitely if you are using an earlier version of Word as it is a recent
addition to VBA.

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 
D

Diana Morrison

"Replace" is highlighted.

I have Word 2003. I have 2007 at home but hey, this is the office. :) Diana
 
D

Doug Robbins - Word MVP

It should work with 2003 and 2007. Do you have this line of code

myDoc.SaveAs myPath & Replace(myName, "AE", "MA")

exactly as shown? It certainly worked for me.

If you have some text in an ordinary document that contains AE and run the
following macro,

MsgBox Replace(Selection.Text, "AE", "MA")

what happens?

--
Hope this helps.

Please reply to the newsgroup unless you wish to avail yourself of my
services on a paid consulting basis.

Doug Robbins - Word MVP
 

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