replace file names characters "_" with " " in folders and multiple subfolders with more subfolders

sachs_v5

New Member
Joined
Dec 26, 2018
Messages
14
Hello All,

I'm new in the forum and after exploring the multiple (great) threads in the forum i have managed to create VBA code to:

- list all files in folder, subfolder and more subfolders using FSO function and loop calls of the same to get all files captured from path in designated Range;

Now i am struggling to use FSO function to replace file name character underscores "_" with spaces " ".

I got it to work but solely to the files in initial folder of designated path in Range (B2 cell).

So i kindly solicit help from the experts around here.

PS: If you can include a Msgbox count to pop-up something close to "x files renamed" it would be great!

Cheers and thanks to the contributions.

Regards,

sachs_v5
 
Hi,
Much appreciated. I Will give it a go on Monday. Wish you and all forum users the best success in 2019.
Cheers Kenneth,

sachs_v5
 
Upvote 0

Excel Facts

Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
Hello,

Im getting again run time error 75 for new code part "case else: error ierr". I am positive that file and path exists and file is not open. I suspect is related with subfolder structure.
Going to paste the code in next thread.

Cheers,

sachs_v5
 
Upvote 0
Happy New Year!

Current code is # Sub RenameFiles()

'set variables

Dim a, i As Long, j As Long, fn$, fn2$, p$, fso As Object

If Range("B7") = 0 Then

MsgBox "No files captured! Please capture files.", vbCritical, "Rename files"

Else

a = aFFs(Range("C2"), , True)

If Not IsArray(a) Then Exit Sub

Set fso = CreateObject("Scripting.FileSystemObject")

For j = LBound(a) To UBound(a)

p = fso.GetParentFolderName(a(j)) & ""

fn = fso.GetFileName(a(j))

If InStr(fn, "_") > 0 Then

fn2 = p & Replace(fn, "_", " ")

'If InStr(fn, " ") > 0 Then

'fn2 = p & Replace(fn, " ", "_")

If Not IsFileOpen(CStr(a(j))) And Not fso.FileExists(fn2) Then

'Name a(j) As fn2

fso.MoveFile a(j), fn2

i = i + 1

Else 'in case of error

Debug.Print "Overwrite issue?", fn2

End If

End If

Next j

Select Case i

Case 0

MsgBox "No files were renamed!", vbCritical, "Rename Files"

Case 1

MsgBox "1 file was renamed", vbExclamation, "Rename Files"

Case Else

MsgBox i & " files renamed", vbExclamation, "Rename Files"

End Select

Set fso = Nothing

End If

End Sub

'Set extraSwitches, e.g. "/ad", to search folders only.

'MyDir should end in a "" character unless searching by wildcards, e.g. "x:\test\t*

'Command line switches for the shell's Dir, http://ss64.com/nt/dir.html

Function aFFs(myDir As String, Optional extraSwitches = "", _

Optional tfSubFolders As Boolean = False) As Variant

Dim s As String, p As String, a() As String, v As Variant

Dim b() As Variant, i As Long, fso As Object

If tfSubFolders Then

s = CreateObject("Wscript.Shell").Exec("cmd /c dir " & _

"""" & myDir & """" & " /b /s " & extraSwitches).StdOut.ReadAll

Else

Set fso = CreateObject("Scripting.FileSystemObject")

p = fso.GetParentFolderName(myDir) & ""

s = CreateObject("Wscript.Shell").Exec("cmd /c dir " & _

"""" & myDir & """" & " /b " & extraSwitches).StdOut.ReadAll

End If

a() = Split(s, vbCrLf)

If UBound(a) = -1 Then

MsgBox myDir & " not found.", vbCritical, "Macro Ending"

Exit Function

End If

ReDim Preserve a(0 To UBound(a) - 1) As String 'Trim trailing vblfcr

For i = 0 To UBound(a)

If Not tfSubFolders Then

s = Left$(myDir, InStrRev(myDir, ""))

'add the folder name

a(i) = p & a(i)

End If

Next i

Set fso = Nothing

aFFs = sA1dtovA1d(a)

End Function

Function sA1dtovA1d(strArray() As String) As Variant

Dim varArray() As Variant, i As Long

ReDim varArray(LBound(strArray) To UBound(strArray))

For i = LBound(strArray) To UBound(strArray)

varArray(i) = CVar(strArray(i))

Next i

sA1dtovA1d = varArray()

End Function

Function IsFileOpen(FileName As String)

Dim iFilenum As Long

Dim iErr As Long

On Error Resume Next

iFilenum = FreeFile()

Open FileName For Input Lock Read As #iFilenum

Close iFilenum

iErr = Err

On Error GoTo 0

Select Case iErr

Case 0: IsFileOpen = False

Case 70: IsFileOpen = True

Case Else: Error iErr

End Select

End Function

Function IsWorkbookOpen(stName As String) As Boolean

Dim Wkb As Workbook

On Error Resume Next ' In Case it isn't Open

Set Wkb = Workbooks(stName)

If Not Wkb Is Nothing Then IsWorkbookOpen = True

'Boolean Function assumed To be False unless Set To True

End Function

Sub callrenamefiles()

CarryOn = MsgBox("Are you sure you wish to proceed with rename action?" & vbLf & vbLf & "This action is irreversible and will impact all files in selected path!", vbYesNo + vbExclamation, "Rename files")

If CarryOn = vbYes Then

Call RenameFiles

End If

End Sub#

Appreciated for your review and inputs why error 75 still pops up.
 
Upvote 0
Hi,

Code posted in #13 continues to throw error 75 path/file not found.

When i debug it goes to "Case Else: Error iErr", and i just can't get why.

Some recap facts:

- running macro to list all files in folder and subfolders - No issues, all files are listed in Wb;

- running macro#13 to replace "_" with " " in filenames of all listed files from range given in cell C2 (same files as listed in macro to list all files);

- i'm working in a network. Absolutely sure none of the files listed is open elsewhere (other user) or is a read-only file;

This said, if any of the contributors of the forum has any suggestion it would be very appreciated.

Cheers,


sachs_v5
 
Upvote 0
I think it may be a permissions issue. You said you did not have antivirus active.

I guess you could try some debug.print lines to do some troubleshooting...

Code:
Sub Main()
  Dim a, i As Long, j As Long, fn$, fn2$, p$, fso As Object
  
  a = aFFs("C:\Users\lenovo1\Dropbox\Excel\t\", , True)
  'a = aFFs("C:\Users\hobs0003\Dropbox\Excel\t", , True)
  If Not IsArray(a) Then Exit Sub
  
  Set fso = CreateObject("Scripting.FileSystemObject")
  For j = LBound(a) To UBound(a)
    p = fso.GetParentFolderName(a(j)) & "\"
    fn = fso.getfilename(a(j))
    
    If InStr(fn, "_") > 0 Then
      fn2 = p & Replace(fn, "_", " ")
    'If InStr(fn, " ") > 0 Then
      'fn2 = p & Replace(fn, " ", "_")
      
Debug.Print a(j), IsFileOpen(CStr(a(j)))
'https://docs.microsoft.com/en-us/office/vba/language/reference/user-interface-help/getattr-function?f1url=https%3A%2F%2Fmsdn.microsoft.com%2Fquery%2Fdev11.query%3FappId%3DDev11IDEF1%26l%3Den-US%26k%3Dk(vblr6.chm1008929)%3Bk(TargetFrameworkMoniker-Office.Version%3Dv16)%26rd%3Dtrue#return-values
Debug.Print fn2, fso.filexists(fn2), GetAttr(fn2) And vbReadOnly

      If Not IsFileOpen(CStr(a(j))) And Not fso.fileexists(fn2) Then
        'Name a(j) As fn2
        fso.MoveFile a(j), fn2
        i = i + 1
        Else 'Boo boo...
        Debug.Print "Overwrite issue?", fn2
      End If
    End If
  Next j
  
  Select Case i
    Case 0
      MsgBox "No files were replaced."
    Case 1
      MsgBox "One file was replaced."
    Case Else
     MsgBox "Files replaced: " & i
  End Select
  
  Set fso = Nothing
End Sub
 
Upvote 0
Hi Kenneth,

I will try it tomorrow. To all due respect, i find it strange that i can choose a path (last subfolder where files are located) and replace filenames but when i select initial path (1st folder of many folders and subfolders) the run time error 75 pops up.

Meaning, i can get it to work only if i select the folder where files are located, instead of being able to select initial folder where multiple subfolders with many subfolders and replace all filenames that match case in macro "_" with " ".

I am very thankfull for your help.

Regards,

sachs_v5
 
Upvote 0
Hi,

Issue persists and run time error 75 pops before the code reaches the last added debug code part.
I confirm that if my range in cell is last folder where files are located there is no issue and macro runs smoothly. But when range in cell is folder with no files and subfolders with files then ir pops error 75. I debug and takes me to case else: err ierr.
Asking help please.

Cheers,

sachs_v5
 
Upvote 0
Hi

Im using Excel 2010 and sample folder is located in my c:\ drive. What more information can i Share?

Cheers
 
Upvote 0

Forum statistics

Threads
1,215,731
Messages
6,126,539
Members
449,316
Latest member
sravya

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top