Avatar of damixa
damixaFlag for Denmark asked on

Create a macro to trim selected cells in excel

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.
Microsoft ApplicationsMicrosoft OfficeMicrosoft Excel

Avatar of undefined
Last Comment

8/22/2022 - Mon
Jorge Paulino

Log in or sign up to see answer
Become an EE member today7-DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform
Sign up - Free for 7 days
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.
See how we're fighting big data
Not exactly the question you had in mind?
Sign up for an EE membership and get your own personalized solution. With an EE membership, you can ask unlimited troubleshooting, research, or opinion questions.
ask a question

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)
End If
Application.ScreenUpdating = True
End Sub

Open in new window

I started with Experts Exchange in 2004 and it's been a mainstay of my professional computing life since. It helped me launch a career as a programmer / Oracle data analyst
William Peck