Link to home
Start Free TrialLog in
Avatar of damixa
damixaFlag for Denmark

asked on

Create a macro to trim selected cells in excel

Hi,
Im looking to create a macro to trim the selected cells. By trim i mean get rid of extra space on both sides. I kow I can do this with with the function TRIM() but i was looking to do this with a macro since there are several columns to be trimmed, and it would save me a lot of time to select the cells and just run the macro.

thanks a lot.
ASKER CERTIFIED SOLUTION
Avatar of Jorge Paulino
Jorge Paulino
Flag of Portugal image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of damixa

ASKER

Thanks a bunch, much appreciated.
The code will run faster if you excluded cells that were blank and turned screen updating off.
Sub Trimmer()
Dim cel As Range, rg As Range
Application.ScreenUpdating = False
Set rg = Selection.SpecialCells(xlCellTypeConstants)
If Not rg Is Nothing Then
    For Each cel In rg.Cells
        cel = Application.Trim(cel)
    Next
End If
Application.ScreenUpdating = True
End Sub

Open in new window