jmckeone
Well-known Member
- Joined
- Jun 3, 2006
- Messages
- 550
I receive a weekly spreadsheet which contains a couple columns with text strings. Frequently there are special characters, leading and trailing spaces and the occassional carriage return (if that is what the thing at the end that looks like a lowercase square is). I've been using the following bit of code to run the trim function for leading and trailing spaces but would like to update the code to remove any other innocuous characters.
Even after running this on the following example you'll see there are still elements left behind.
[/quote]
Code:
Sub TrimAllUsed()
' Turn off screenupdating:
Application.ScreenUpdating = False
' Select used area
Dim BeginingRow, BeginingColumn, NumberOfUsedRows, NumberOfUsedColumns As Integer
BeginingRow = 1
BeginingColumn = 1
NumberOfUsedRows = ActiveSheet.UsedRange.Rows.Count
NumberOfUsedColumns = ActiveSheet.UsedRange.Columns.Count
Range(Cells(BeginingRow, BeginingColumn), Cells(NumberOfUsedRows, NumberOfUsedColumns)).Select
' Trim Selected area
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
Dim cell As Range
'Also Treat CHR 0160, as a space (CHR 032)
Selection.Replace What:=Chr(160), Replacement:=Chr(32), _
LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False
'Trim in Excel removes extra internal spaces, VBA does not
On Error Resume Next 'in case no text cells in selection
For Each cell In Intersect(Selection, _
Selection.SpecialCells(xlConstants, xlTextValues))
cell.Value = Application.Trim(cell.Value)
Next cell
On Error GoTo 0
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub
Even after running this on the following example you'll see there are still elements left behind.