Haris Ahmed
Haris Ahmed

Reputation: 83

VBScript Renaming File Code Issue

I wrote a simple vbscript to rename files in a particular folder. Specifically to remove particular content from the filname.

The Script I wrote (listed below) runs fine but the highlighted part (second IF-THEN statement) doesn't run. I can't figure out whats wrong with the code. I plan to add more IF-THEN statement to remove particular content from file names.

I'm a novice at this so please be patient with me. Can anyone help?

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="C:\Users\Admin2\Downloads\Compressed"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    strFileName = strFile.Name

    If InStr(strFileName,"(2014)") > 0 Then           
        strNewFileName = Replace(strFileName,"(2014)","")
        strFile.Name = strNewFileName
    End If        
    **If InStr(strFileName,"(digital)") > 0 Then           
        strNewFileName = Replace(strFileName,"(digital)","")
        strFile.Name = strNewFileName
    End If**
Next 

Upvotes: 0

Views: 198

Answers (2)

Saad Bashir
Saad Bashir

Reputation: 4519

I hope the following code helps

  Set objFS = CreateObject("Scripting.FileSystemObject")
    strFolder="pathtofolder"
    Set objFolder = objFS.GetFolder(strFolder)
    For Each objFile In objFolder.Files
            ObjFileName = ObjFile.Name
            NewFileName = Replace(Replace(ObjFileName,"(2014)",""),"(digital)","")
            Set fileSystemObject = CreateObject("Scripting.FileSystemObject")
            If fileSystemObject.FileExists(NewFileName) Then
            Else
            ObjFile.Name = Trim(NewFileName)
            End If
        Next 

Upvotes: 0

Ekkehard.Horner
Ekkehard.Horner

Reputation: 38745

Type prefix fraud detected:

For Each strFile In objFolder.Files

"strFile" should be "objFile". Dangerous extra variable in:

strFileName = strFile.Name

The variable "strFileName" will get stale if you change "objFile.Name". Use a variable to hold the new/desired name instead.

strNewFileName = objFile.Name

Renaming the file twice will loose changes on the way. Modify "strNewFileName" (in steps or all at once:

strNewFileName = Replace(Replace(strNewFileName, "(2014)", ""), "(digital)", "")

; you don't really need the If guard, because Replace won't change strings that don't contain the target).

Check for .FileExists(strNewFileName) before you do the rename.

Can you prove that there are file names that contain "(digita1)" <-- mark the digit 1) exactly? Lower vs. upper case? A nasty blank?

Upvotes: 2

Related Questions