Clear All Occurences of Extra White Space

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 WhiteSpacesSub ClearSpace(withSpace As String, withoutSpace As String)If withSpace = withoutSpace Then  MsgBox "Both Files Same", vbCritical, "Error:"  Exit SubEnd IfDim fs As ObjectDim tmpWhiteSpace As ObjectDim tmpFile As ObjectDim var_txt As StringDim pos As LongSet 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)  Wend  'For removing all the spaces at the ends  var_txt = LTrim(RTrim(var_txt))   If (var_txt  "") Then     tmpFile.WriteLine var_txt  End IfLooptmpWhiteSpace.ClosetmpFile.Close 'Closes and Saves the contentsEnd Sub


Share the Post: