Browse DevX
Sign up for e-mail newsletters from DevX

Tip of the Day
Language: VB
Expertise: Intermediate
Dec 28, 2006



Building the Right Environment to Support AI, Machine Learning and Deep Learning

Clear All Occurences of Extra White Space

This function clears all occurences of extra white space (spaces, tabs, blank lines) and programming comments beginning with ';' in a file and saves the cleaned file as another file.

It uses the following I/P arguments:

  • The inbuilt Ltrim and Rtrim functions can remove spaces only on the sides but not internal ones. This function can also remove the extra internal spaces.
  • Filepath of the file to be cleaned
  • Filepath of the cleaned file to be saved
You can use the Loop and Replace function to find all adjacent spaces " " and replace them with single spaces " ". Keep doing this until the entire string becomes proper.

'Sub for clearing WhiteSpaces
Sub ClearSpace(withSpace As String, withoutSpace As String)

If withSpace = withoutSpace Then
  MsgBox "Both Files Same", vbCritical, "Error:"
  Exit Sub
End If

Dim fs As Object
Dim tmpWhiteSpace As Object
Dim tmpFile As Object
Dim var_txt As String
Dim pos As Long

Set fs = CreateObject("Scripting.FileSystemObject")
Set tmpWhiteSpace = fs.OpenTextFile(withSpace, 1)
Set tmpFile = fs.CreateTextFile(withoutSpace, True)

Do While (Not tmpWhiteSpace.AtEndOfStream)
  var_txt = tmpWhiteSpace.readLine
  'Remove comments that begin with ';'
  pos = InStr(1, var_txt, ";", vbTextCompare)
  If pos <> 0 Then
     var_txt = Left(var_txt, pos - 1)
  End If
  'Remove Internal Extra White Spaces
  While var_txt <> Replace(var_txt, "  ", " ", 1, -1, vbTextCompare)
    var_txt = Replace(var_txt, "  ", " ", 1, -1, vbTextCompare)

  'For removing all the spaces at the ends
  var_txt = LTrim(RTrim(var_txt)) 
  If (var_txt <> "") Then
     tmpFile.WriteLine var_txt
  End If

tmpFile.Close 'Closes and Saves the contents
End Sub
Sameer Palande
Thanks for your registration, follow us on our social networks to keep up-to-date