Results 1 to 7 of 7

Thread: Trim all Cells in a Worksheet - VBA

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #2
    Forum Guru Rick Rothstein's Avatar
    Join Date
    Feb 2012
    Posts
    662
    Rep Power
    15
    Here is a UDF (user defined function) that I developed which will clean and trim the text passed into it. The trim operation is identical to Excel's worksheet TRIM function; however, the clean is slightly different. It cleans some additional non-printing characters that Excel's CLEAN function does not handle. Those additional characters are delineated here...

    Remove spaces and nonprinting characters from text - Support - Office.com

    I also included an optional argument to convert non-breaking spaces (ASCII 160) to real spaces (ASCII 32). Because non-breaking spaces are such a problem when copying text from the web, I defaulted this optional argument to True (meaning non-breaking space will be converted into true spaces and then handled, along with existing spaces, by the trim operation).

    Code:
    Function CleanTrim(ByVal S As String, Optional ConvertNonBreakingSpace As Boolean = True) As String
      Dim X As Long, CodesToClean As Variant
      CodesToClean = Array(0, 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, 127, 129, 141, 143, 144, 157)
      If ConvertNonBreakingSpace Then S = Replace(S, Chr(160), " ")
      For X = LBound(CodesToClean) To UBound(CodesToClean)
        If InStr(S, Chr(CodesToClean(X))) Then S = Replace(S, Chr(CodesToClean(X)), "")
      Next
      CleanTrim = WorksheetFunction.Trim(S)
    End Function
    For those reading this thread who are new to UDFs, they are easy to install and use. To install it, simply press ALT+F11 to go into the VB editor and, once there, click Insert/Module on its menu bar, then copy/paste the above code into the code window that just opened up. That's it.... you are done. You can now use CleanTrim just like it was a built-in Excel function. For example,

    =CleanTrim(A1)
    Last edited by Rick Rothstein; 07-19-2013 at 07:24 AM.

Similar Threads

  1. Replies: 13
    Last Post: 06-10-2013, 09:05 AM
  2. Print Nth Worksheet To Mth Worksheet using VBA
    By Ryan_Bernal in forum Excel Help
    Replies: 2
    Last Post: 02-28-2013, 06:57 PM
  3. Search a last digit e.g 0 and trim to give rest
    By excel_learner in forum Excel Help
    Replies: 4
    Last Post: 01-22-2013, 07:02 PM
  4. Trim Text after 3rd Underscore but retain format
    By trankim in forum Excel Help
    Replies: 4
    Last Post: 05-13-2012, 10:44 AM
  5. Sort Worksheet by Color VBA
    By Admin in forum Excel and VBA Tips and Tricks
    Replies: 0
    Last Post: 10-25-2011, 02:25 AM

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •