0

I am trying to remove the leading and trailing spaces in an excel sheet. I have a code that is currently doing that but it is running through the entire sheet. I would like to select a range, instead of the whole sheet to save time.

I tried using a code already but i need to simplify to make the process faster.

Dim r As Range
For Each r In ActiveSheet.UsedRange
v = r.Value
If v <> "" Then
If Not r.HasFormula Then
r.Value = Trim(v)
End If
End If
Next r

This code will remove spaces from the entire sheet.

4
  • 1
    Instead of using UsedRange, why not Selection? Or get the range from an input box. Commented Aug 21, 2019 at 18:05
  • 1
    OR Find the last row and the last column and then construct your range Commented Aug 21, 2019 at 18:18
  • If you really want to speed this up, you may want to capture your range as a variant array, make your adjustments to the array, then transpose the array back to your sheet. Commented Aug 21, 2019 at 19:18
  • If you don't mind using an add-in instead of coding this yourself, I can recommend asap-utilities.com It is an indispensable tool for me. Commented Aug 21, 2019 at 19:24

1 Answer 1

2

perhaps:

Option Explicit
Sub trimConstants()
    Dim R As Range, C As Range
    Dim WS As Worksheet

Set WS = Worksheets("sheet2") 'better than using `ActiveSheet`
Set R = WS.Cells.SpecialCells(xlCellTypeConstants)

For Each C In R
    C = Trim(C)
Next C

End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.