Sub TrimText()
Dim lRow As Integer
With Worksheets("Sheet1")
lRow = .Range("E2").End(xlDown).Row
For i = 2 To lRow
.Cells(i, "E").Value = Trim(.Cells(i, "E").Value)
Next i
End With
End Sub
Sub TrimColumnE()
Dim Addr As String
Addr = "E1:E" & Cells(Rows.Count, "E").End(xlUp).Row
Range(Addr) = Evaluate("IF(" & Addr & "="""","""",TRIM(" & Addr & "))")
End Sub
For those who might read this thread in the future... DushiPunda's solution will only trim outside space. If you want to apply Excel's TRIM function which does that plus it collapses multiple adjacent internal spaces down to single spaces, then you can use this macro...
Code:Sub TrimColumnE() Dim Addr As String Addr = "E1:E" & Cells(Rows.Count, "E").End(xlUp).Row Range(Addr) = Evaluate("IF(" & Addr & "="""","""",TRIM(" & Addr & "))") End Sub
True, but the reason I did not suggest that is I wanted to offer a solution that did not make use of a loop.Or DushiPunda's code could be changed to :
.Cells(i, "E").Value = Application.Trim(.Cells(i, "E").Value)
True, but the reason I did not suggest that is I wanted to offer a solution that did not make use of a loop.
Sub TrimColumnE()
[E:E] = [IFERROR(TRIM(E:E),"""")]
End Sub
That depends highly on how the loop is written and/or what the loop is doing... it is definitely not the case with this OP's request (see below).Normally, the only reason to avoid a worksheet object loop is to reduce run-time - any such reduction is often immaterial.
Not always... it depends on what the code is doing. You might be surprised to find out that the Evaluate method is faster than the "put the range in an array, loop the array, and put the result back" method you suggested, not enough time difference to matter in human terms, but Evaluate was definitely faster (on my computer, of course). I Tested with 200,000 cells in a column... Evaluate took 0.74 seconds whereas the array method took 1.13 seconds. Here is the array code that I used...In the event it is material, another approach could be to put the range in an array, loop the array, and put the result back to the worksheet - this could well be quicker in some circumstances than using Evaluate.
Sub TrimColumnE()
Dim R As Long, Data As Variant
Data = Range("E1", Cells(Rows.Count, "E").End(xlUp))
For R = 1 To UBound(Data)
Data(R, 1) = Application.Trim(Data(R, 1))
Next
Range("E1").Resize(UBound(Data)) = Data
End Sub
It took 2.6 seconds for this code to process the 200,000 rows of data.The Evaluate method could also be written like this (although probably a bit slow) :
Code:Sub TrimColumnE() [E:E] = [IFERROR(TRIM(E:E),"""")] End Sub