TRIM in VBA with Substitute

jam1531

New Member
Joined
Jan 5, 2015
Messages
29
Hello,

I have searched and t this point have not found anything that is very helpful with the substitute function in VBA. I am unsure why but sometimes TRIM does not remove the space after a the word in a cell.

Someone gave me the following which seems to work

=TRIM(SUBSTITUTE(A1,CHAR(160),CHAR(32)))

However I want to create a personal macro that will run this in each cell that is currently selected. For some reason the below code I have built out so far does not work. What am I missing or is there an easier way altogether? I believe the problem occurs with the substitute. Any help appreciated.



Code:
Sub tested()

Dim cell As Range
For Each cell In Selection


Selection.Value = TRIM(Substitute(Selection.Value, Chr(160), Chr(32)))


Next


End Sub
 

Excel Facts

Which Excel functions can ignore hidden rows?
The SUBTOTAL and AGGREGATE functions ignore hidden rows. AGGREGATE can also exclude error cells and more.
VBA doesn't have a SUBSTITUTE function, try using Replace instead.
Code:
Sub tested()
Dim cell As Range

    For Each cell In Selection
        Cell.Value = Trim(Replace(Cell.Value, Chr(160), Chr(32)))
    Next

End Sub
 
Upvote 0
Another thing to note, unlike the Xl function, the VBA trim does not remove multiple spaces between words, so you may want
Code:
Cell.Value = Application.Trim(Replace(Cell.Value, Chr(160), Chr(32)))
 
Upvote 0

Forum statistics

Threads
1,215,695
Messages
6,126,263
Members
449,307
Latest member
Andile

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top