Speed Up Trim Macro

Dazzawm

Well-known Member
Joined
Jan 24, 2011
Messages
3,786
Office Version
  1. 365
Platform
  1. Windows
I was given the code below to run a Trim Macro. I have 10000 rows and 30 columns of data for it check and it takes forever and sometimes freezes. Is there anyway it can be speeded up please?

Code:
Sub trimCells()
Application.ScreenUpdating = False
  For Each c In ActiveSheet.UsedRange
    c.Value = WorksheetFunction.Trim(c.Value)
  Next c
Application.ScreenUpdating = True
End Sub
 

Excel Facts

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
This should be quicker:

Code:
Public Sub TrimIt()
    With ActiveSheet.UsedRange
        .Value = Evaluate("if(row(),trim(" & .Address & "))")
    End With
End Sub
 
Upvote 0
Will this remove extra spaces between words etc.?
 
Upvote 0
Yes, multiple spaces will be reduced to just one space. Trailing and leading spaces will be removed entirely.
 
Upvote 0
Try:
Code:
Sub EatinMePenguin()
 
Dim x As Long, y As Long, a As Long, b As Long
 
With Application
    .ScreenUpdating = False
    .Calculation = xlCalculationManual
End With
 
y = Cells.Find(what:="*", after:=Range("A1"), searchorder:=xlByColumns, searchdirection:=xlPrevious).Column
x = Cells.Find(what:="*", after:=Range("A1"), searchorder:=xlByRows, searchdirection:=xlPrevious).Row
 
For a = 1 To x
    For b = 1 To y
        If Len(Cells(a, b)) > 0 Then Cells(a, b).Value = Trim(Cells(a, b))
    Next b
Next a
 
With Application
    .ScreenUpdating = True
    .Calculation = xlCalculationAutomatic
End With
 
End Sub
 
Last edited:
Upvote 0
Not quite a copy and paste. The evaluate method evaluates a formula yet returns a constant. This method allows us to handle the entire used range in one hit.
 
Upvote 0

Forum statistics

Threads
1,224,516
Messages
6,179,231
Members
452,898
Latest member
Capolavoro009

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top