cellMatrix.net

Spreadsheet Modeling and Related Topics

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 Thursday, November 19, 2009 | Comments (1) | Permalink

Page 1 of 1 pages

Statistics

  • Total Entries - 136
  • Current Viewers - 33

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