Results 1 to 7 of 7

Thread: Trim all Cells in a Worksheet - VBA

  1. #1
    Administrator Admin's Avatar
    Join Date
    Mar 2011
    Posts
    1,123
    Rep Power
    10

    Lightbulb Trim all Cells in a Worksheet - VBA

    Hi All,

    Here is a VBA routine to Trim as well as Clean all used range in a worksheet.

    Code:
    '// Developed by Kris @ ExcelFox.com
    Sub TRIMALL(ByRef Sht As Worksheet)
        
        Dim aAddr       As String
        Dim MaxLen      As Long
        Dim v           As Variant
        Dim r           As Long
        Dim c           As Long
        Dim Rng         As Range
        Dim a           As Long
        
        On Error Resume Next
        Set Rng = Sht.UsedRange.SpecialCells(2, 6)
        On Error GoTo 0
        
        If Rng Is Nothing Then Exit Sub
        
        For a = 1 To Rng.Areas.Count
            With Rng.Areas(a)
                aAddr = "'" & Sht.Name & "'!" & .Address
                MaxLen = Evaluate("max(len(" & aAddr & "))")
                If MaxLen > 255 Then v = .Value
                .Value = Evaluate("if(len(" & aAddr & "),clean(trim(" & aAddr & "))," & aAddr & ")")
                If MaxLen > 255 Then
                    If IsArray(v) Then
                        For r = 1 To UBound(v, 1)
                            For c = 1 To UBound(v, 2)
                                If Len(v(r, c)) > 255 Then .Cells(r, c).Value = Application.Clean(Application.Trim(v(r, c)))
                            Next
                        Next
                    Else
                        .Cells(1).Value = Application.Clean(Application.Trim(v))
                    End If
                End If
            End With
        Next
        
    End Sub
    and call the routine like..


    Code:
    Sub Test()
    
        TRIMALL ThisWorkbook.Worksheets("Sheet1")
    
    End Sub
    Enjoy !!
    Last edited by Admin; 08-21-2015 at 08:22 AM. Reason: code edited
    Cheers !

    Excel Range to BBCode Table
    Use Social Networking Tools If You Like the Answers !

    Message to Cross Posters

    @ Home - Office 2010/2013/2016 on Win 10 (64 bit); @ Work - Office 2016 on Win 10 (64 bit)

  2. #2
    Forum Guru Rick Rothstein's Avatar
    Join Date
    Feb 2012
    Posts
    662
    Rep Power
    13
    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.

  3. #3
    Administrator Admin's Avatar
    Join Date
    Mar 2011
    Posts
    1,123
    Rep Power
    10
    Hi Rick,

    Cheers !

    Excel Range to BBCode Table
    Use Social Networking Tools If You Like the Answers !

    Message to Cross Posters

    @ Home - Office 2010/2013/2016 on Win 10 (64 bit); @ Work - Office 2016 on Win 10 (64 bit)

  4. #4
    Junior Member
    Join Date
    Jan 2014
    Posts
    6
    Rep Power
    0
    Quote Originally Posted by Rick Rothstein View Post
    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)
    I managed to get a character (no merit in this) that your function does not eliminate, and I would really understand what it is, because it is driving me nuts. After some experimenting, I can say that:
    1) the cell IS cleared simply by canceling it (delete key on the keyboard) or by the equivalent VBA ClearContents method, but NOT by Clean or Trim methods or functions
    2) the cell IS counted by COUNTA function (so there is something in it...or there isn't?)
    3) the cell IS counted by COUNTBLANK function (so there is nothing in there...)
    4) LEN function applied to the cell gives 0 (zero) result

    I don't know if I can upload a small workbook with this cell in it, if so please explain. This ghost keep appearing in a database I am working with for a friend, and disrupts a number of pivot tables used for statistics. By the way, the pivot tables count these cells as non empty, whereas if you use the simple excel filter for non-blank function (the one on top of the column) these cells are correctly not counted.
    Cheers
    Robert, Italy

  5. #5
    Junior Member
    Join Date
    Oct 2012
    Posts
    2
    Rep Power
    0
    Rick,

    I just stumbled upon this when looking for a means to clean a range of cells containing IP addresses, which I needed to be able to ping.

    Of course, if I'd just checked for spaces in the first place before getting Network Services to check my permissions against a range of servers that I was actually able to access all the time...

    But, my idiocy aside, this is brilliant and did the job perfectly - thank you very much! :-)

    Pete



    https://www.youtube.com/channel/UCnxwq2aGJRbjOo_MO54oaHA
    https://www.youtube.com/watch?v=oVb1RfcSHLM&lc=UgwTq-jZlZLnLQ5VB8Z4AaABAg.9Hroz-OyWog9tYjSMc1qjA
    https://www.youtube.com/watch?v=0pbsf6sox34&lc=Ugxp9JFvvejnqA68W1t4AaABAg
    https://www.youtube.com/watch?v=kfQC-sQxMcw&lc=UgyCxQWypNIhG2nUn794AaABAg.9q1p6q7ah839tUQl_92m vg
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgyOh-eR43LvlIJLG5p4AaABAg.9isnKJoRfbL9itPC-4uckb
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=Ugy1B1aQnHq2WbbucmR4AaABAg.9isY3Ezhx4j9itQLuif2 6T
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgxxajSt03TX1wxh3IJ4AaABAg.9irSL7x4Moh9itTRqL7d Qh
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=Ugxa2VYHMWJWXA6QI294AaABAg.9irLgSdeU3r9itU7zdnW Hw
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgwJAAPbp8dhkW2X1Uh4AaABAg.9iraombnLDb9itV80HDp Xc
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgzIzQ6MQ5kTpuLbIuB4AaABAg.9is0FSoF2Wi9itWKEvGS Sq
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgykemWTw-fGoPwu8E14AaABAg.9iECYNx-n4U9iK75iCEaGN
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgykemWTw-fGoPwu8E14AaABAg.9iECYNx-n4U9iK7XF33njy
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugy_1xkcndYdzUapw-J4AaABAg.9iGOq_leF_E9iKCSgpAqA1
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugy_1xkcndYdzUapw-J4AaABAg.9iGOq_leF_E9iKCy--3x8E
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwNaJiNATXshvJ0Zz94AaABAg.9iEktVkTAHk9iF9_pdsh r6
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgykemWTw-fGoPwu8E14AaABAg.9iECYNx-n4U9iFAZq-JEZ-
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgxV2r7KQnuAyZVLHH54AaABAg.9iDVgy6wzct9iFBxma9z XI
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugx12mI-a39T41NaZ8F4AaABAg.9iDQqIP56NV9iFD0AkeeJG
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwnYuSngiuYaUhEMWN4AaABAg.9iDQN7TORHv9iFGQQ5z_ 3f
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwJ3yzdk_EE98dndmt4AaABAg.9iDLC2uEPRW9iFGvgk11 nH
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgyDWAVqCa4yMot463x4AaABAg.9iH3wvUZj3n9iHnpOxOe Xa
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwvLFdMEAba5rLHIz94AaABAg.9iGReNGzP4v9iHoeaCpT G8
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugy_1xkcndYdzUapw-J4AaABAg.9iGOq_leF_E9iHpsWCdJ5I
    https://www.youtube.com/channel/UCnxwq2aGJRbjOo_MO54oaHA
    Last edited by DocAElstein; 09-13-2023 at 10:47 AM.

  6. #6
    Junior Member
    Join Date
    Aug 2015
    Posts
    1
    Rep Power
    0

    Error running code

    [QUOTE=Admin;466]Hi All,


    Hi this code is almost a lifesaver for me, I'm just having one problem: I run the code and then get an error 13 'mismatch.' I tried debugging it and it pointed me to this line: For r = 1 To UBound(v, 1).

    Unfortunately I'm an extreme amateur with anything vba in excel. Any suggestions or help would be most welcome.

    PS. What I'm trying to do is clean up a bunch of cells in my worksheet that have horrible HTML code in there. I'm not trying to remove the tags just all the empty white space, line breaks, and tab characters that are in the cell.



    https://www.youtube.com/channel/UCnxwq2aGJRbjOo_MO54oaHA
    https://www.youtube.com/watch?v=oVb1RfcSHLM&lc=UgwTq-jZlZLnLQ5VB8Z4AaABAg.9Hroz-OyWog9tYjSMc1qjA
    https://www.youtube.com/watch?v=0pbsf6sox34&lc=Ugxp9JFvvejnqA68W1t4AaABAg
    https://www.youtube.com/watch?v=kfQC-sQxMcw&lc=UgyCxQWypNIhG2nUn794AaABAg.9q1p6q7ah839tUQl_92m vg
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgyOh-eR43LvlIJLG5p4AaABAg.9isnKJoRfbL9itPC-4uckb
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=Ugy1B1aQnHq2WbbucmR4AaABAg.9isY3Ezhx4j9itQLuif2 6T
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgxxajSt03TX1wxh3IJ4AaABAg.9irSL7x4Moh9itTRqL7d Qh
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=Ugxa2VYHMWJWXA6QI294AaABAg.9irLgSdeU3r9itU7zdnW Hw
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgwJAAPbp8dhkW2X1Uh4AaABAg.9iraombnLDb9itV80HDp Xc
    https://www.youtube.com/watch?v=vXyMScSbhk4&lc=UgzIzQ6MQ5kTpuLbIuB4AaABAg.9is0FSoF2Wi9itWKEvGS Sq
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgykemWTw-fGoPwu8E14AaABAg.9iECYNx-n4U9iK75iCEaGN
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgykemWTw-fGoPwu8E14AaABAg.9iECYNx-n4U9iK7XF33njy
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugy_1xkcndYdzUapw-J4AaABAg.9iGOq_leF_E9iKCSgpAqA1
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugy_1xkcndYdzUapw-J4AaABAg.9iGOq_leF_E9iKCy--3x8E
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwNaJiNATXshvJ0Zz94AaABAg.9iEktVkTAHk9iF9_pdsh r6
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgykemWTw-fGoPwu8E14AaABAg.9iECYNx-n4U9iFAZq-JEZ-
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgxV2r7KQnuAyZVLHH54AaABAg.9iDVgy6wzct9iFBxma9z XI
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugx12mI-a39T41NaZ8F4AaABAg.9iDQqIP56NV9iFD0AkeeJG
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwnYuSngiuYaUhEMWN4AaABAg.9iDQN7TORHv9iFGQQ5z_ 3f
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwJ3yzdk_EE98dndmt4AaABAg.9iDLC2uEPRW9iFGvgk11 nH
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgyDWAVqCa4yMot463x4AaABAg.9iH3wvUZj3n9iHnpOxOe Xa
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=UgwvLFdMEAba5rLHIz94AaABAg.9iGReNGzP4v9iHoeaCpT G8
    https://www.youtube.com/watch?v=ITI1HaFeq_g&lc=Ugy_1xkcndYdzUapw-J4AaABAg.9iGOq_leF_E9iHpsWCdJ5I
    https://www.youtube.com/channel/UCnxwq2aGJRbjOo_MO54oaHA
    Last edited by DocAElstein; 09-13-2023 at 11:00 AM.

  7. #7
    Administrator Admin's Avatar
    Join Date
    Mar 2011
    Posts
    1,123
    Rep Power
    10
    I have edited my above code.
    Cheers !

    Excel Range to BBCode Table
    Use Social Networking Tools If You Like the Answers !

    Message to Cross Posters

    @ Home - Office 2010/2013/2016 on Win 10 (64 bit); @ Work - Office 2016 on Win 10 (64 bit)

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
  •