Removing Spaces from File Names

For a number of reasons I prefer to never use spaces in file names. Recently Dick Kuslieka at the Daily Dose of Excel posted an interesting VBA technique for removing spaces from file names. John Walkenbach commented with a revision that will allow the same functionality using Excel 2007 and Rick Rothstein commented with another alternative. These snippets are great additions to my VBA toolbox.

Dick's Kuslieka's original post:

Sub RemoveSpaces()
    
    Dim fso As FileSystemObject
    Dim fsoFile As File
    
    Set fso = New FileSystemObject
    
    For Each fsoFile In fso.GetFolder("C:\Tester").Files
        If InStr(1, fsoFile.Name, " ")> 0 Then
            fsoFile.Name = Replace(fsoFile.Name, " ", "_")
        End If
    Next fsoFile
    
End Sub

John Walkenbach's version for Excel 2007:

Sub RemoveSpaces()
    Const Folder As String = "C:\Tester\"
    Dim FileName As String, NewName As String
    FileName = Dir(Folder)
    Do While FileName  ""
        If InStr(1, FileName, " ")> 0 Then
            NewName = Replace(FileName, " ", "_")
            Name Folder & FileName As Folder & NewName
        End If
        FileName = Dir
    Loop
End Sub

and Rick Rothstein commented with another version:

Sub RemoveSpaces()
  Dim Path As String, FileName As String
  Path = "C:\Tester\"  'Note the trailing backslash
  FileName = Dir(Path & "*.*")
  Do While FileName  ""
    Name Path & FileName As Path & Replace(FileName, " ", "_")
    FileName = Dir
  Loop
End Sub

Posted on November 19, 2009 | Filed under: VBA | Comments (1) | Permalink
Page 1 of 1 pages

Comments

Just a note about the codes you posted… your “comment editor” software appears to have remove the greater than/less than symbols (for the “not equal” operator) from the two Do While statements. Perhaps posting those statements this way would be better…

Do While Len(FileName)

Posted by Rick Rothstein (MVP - Excel)  on  12/11  at  10:36 AM
Page 1 of 1 pages

Comment Entry

Name:

Email:

Location:

URL:

Remember my personal information

Notify me of follow-up comments?

Statistics

  • Total Entries - 136
  • Current Viewers - 28

Categories

Entries by Day

Jul - 2010
S M T W T F S
27 28 29 30 1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31

Recent Comments

Syndicate