How to remove part of filename using vbscript

Viewed 295

I have hundreds of filenames with a - (dash) 0 (zero) like V-45X-0892-0.pdf, V-45X-0893-0.pdf and would like to strip the -0 from filename.

Here's what I have but is not working.

folderspec = "C:\Dave\"
strRename = ""

Set fs = CreateObject("Scripting.FileSystemObject")
Set f = fs.GetFolder(folderspec)

For Each f1 In f.Files
    Filename = folderspec & f1.Name
    NewFilename = Replace(Filename, "%-0.pdf""%.pdf", strRename)
    fs.MoveFile Filename, NewFilename
Next

MsgBox "All Done"
1 Answers

Here's code based on your Question with modifications made to the For Each loop. Note that you don't need to use MoveFile, you can simply update the file's Name property directly:

Dim objFSO
Dim objFolder
Dim objFile
Dim sFolderSpec

sFolderSpec = "C:\Dave\"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(sFolderSpec)

For Each objFile In objFolder.Files
    If InStr(objFile.Name, "-0") > 0 Then objFile.Name = Replace(objFile.Name, "-0", "")
Next

MsgBox "All Done"
Related