Reputation: 128
I have got following code for get rid of middle spaces, line feed and Trim
But Trim
doesn't work. What could be the reason?
Sub Replace()
With Sheets("Input_Data").Range("A1:A6300")
'With Sheets("Input_Limits").Range("A1:A6300")
.Cells.Replace " ", " ", xlPart, xlByRows, False
.Cells.Replace vbLf, "", xlPart, xlByRows, False
'.Cells.Trim
End With
End Sub
It gives:
Error - Object doesn't support this property method
Upvotes: 0
Views: 2647
Reputation: 1
Sub DescTrim(Cx As Integer)
Dim Rx As Integer: Rx = 5 'Start at row 5
Dim STrimmed As String
For Rx = 5 To ActiveSheet.UsedRange.Rows.Count
STrimmed = Trim(Cells(Rx, Cx).Value)
While InStr(STrimmed, chr(32) & (chr(32))
STrimmed = Replace(STrimmed, Chr(32) & Chr(32), chr(32))
Wend
Cells(Rx, Cx).Value = STrimmed
Next
End Sub
Upvotes: -1
Reputation: 46365
The following code will do what you are asking for. Note that I am applying the trim operation to all cells in the active sheet; if that is not what you want, you can obviously edit it...
Sub trimAll()
Dim c As Range
For Each c In ActiveSheet.UsedRange.Cells
If Not (IsEmpty(c) Or IsError(c) Or IsFormula(c)) Then
c.Value = Trim(c.Value)
End If
Next c
With ActiveSheet.UsedRange.Cells
.Cells.Replace " ", " ", xlPart, xlByRows, False
.Cells.Replace vbLf, "", xlPart, xlByRows, False
End With
End Sub
Function IsFormula(c)
' use this to test for formulas - don't edit those or they become values!
IsFormula = True
On Error Resume Next
If Left(c.Formula, 1) = "=" Then IsFormula = True Else IsFormula = False
End Function
Upvotes: 1
Reputation: 46365
Since Trim does not support a range, you could add the following:
Dim c as Cell
For each c in .Cells
c.Value = Trim(c.Value)
Next c
Disclaimer: not tested. See other answer for more complete solution.
Upvotes: 0
Reputation: 169284
You cannot use Trim
on a range. The Trim
documentation states:
Trim(string)
The required string argument is any valid string expression.
Also, Trim
is not suited to your task in that it does NOT remove spaces within a string. This is mentioned in the documentation (emphasis added):
Returns a Variant (String) containing a copy of a specified string without leading spaces (LTrim), trailing spaces (RTrim), or both leading and trailing spaces (Trim).
Upvotes: 1