• Skip to main content
  • Skip to header right navigation
  • Skip to site footer

My Online Training Hub

Learn Dashboards, Excel, Power BI, Power Query, Power Pivot

  • Courses
  • Pricing
    • Free Courses
    • Power BI Course
    • Excel Power Query Course
    • Power Pivot and DAX Course
    • Excel Dashboard Course
    • Excel PivotTable Course – Quick Start
    • Advanced Excel Formulas Course
    • Excel Expert Advanced Excel Training
    • Excel Tables Course
    • Excel, Word, Outlook
    • Financial Modelling Course
    • Excel PivotTable Course
    • Excel for Customer Service Professionals
    • Excel for Operations Management Course
    • Excel for Decision Making Under Uncertainty Course
    • Excel for Finance Course
    • Excel Analysis ToolPak Course
    • Multi-User Pricing
  • Resources
    • Free Downloads
    • Excel Functions Explained
    • Excel Formulas
    • Excel Add-ins
    • IF Function
      • Excel IF Statement Explained
      • Excel IF AND OR Functions
      • IF Formula Builder
    • Time & Dates in Excel
      • Excel Date & Time
      • Calculating Time in Excel
      • Excel Time Calculation Tricks
      • Excel Date and Time Formatting
    • Excel Keyboard Shortcuts
    • Excel Custom Number Format Guide
    • Pivot Tables Guide
    • VLOOKUP Guide
    • ALT Codes
    • Excel VBA & Macros
    • Excel User Forms
    • VBA String Functions
  • Members
    • Login
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member
  • Login

Macro remove leading and trailing spaces in cells|VBA & Macros|Excel Forum|My Online Training Hub

You are here: Home / Macro remove leading and trailing spaces in cells|VBA & Macros|Excel Forum|My Online Training Hub

office scripts course

Avatar
sp_LogInOut Log In sp_Registration Register
sp_Search Search
Advanced Search
Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search Search
sp_RankInfo
Lost password?
sp_CrumbsHome HomeExcel ForumVBA & MacrosMacro remove leading and trailing s…
sp_PrintTopic sp_TopicIcon
Macro remove leading and trailing spaces in cells
Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
1
January 15, 2021 - 9:59 am
sp_Permalink sp_Print

How to write a macro to remove leading, trailing spaces, line breaks or hidden character etc etc in the range cells selected.  

I convert the data  from Pivot Table to value but found can not perform the calculation in the converted sheet due to above.[ pls refer attached]

Avatar
Lionel Baijot
Member
Members
Level 0
Forum Posts: 119
Member Since:
September 9, 2020
sp_UserOfflineSmall Offline
2
January 15, 2021 - 3:16 pm
sp_Permalink sp_Print

Hi David,

Here is a code that does what you ask. :

Sub Space()

Dim Ligne As Integer, cell As Range
With Sheets("Sheet2")

'Determines the last line
For Each cell In .UsedRange
'Removes unnecessary and other spaces in the cell
'TAB
cell = Replace(cell, Chr(9), "")
'Line Feed
cell = Replace(cell, Chr(10), "")
'space
cell = Replace(cell, Chr(160), "")
cell = Application.WorksheetFunction.Trim(cell)
cell = Application.WorksheetFunction.Clean(cell)
Next
End With
End Sub

 

BR,

Lionel

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
3
January 15, 2021 - 4:41 pm
sp_Permalink sp_Print

Thanks Lionel, but cells Leading spaces still can not remove.

Avatar
Lionel Baijot
Member
Members
Level 0
Forum Posts: 119
Member Since:
September 9, 2020
sp_UserOfflineSmall Offline
4
January 15, 2021 - 9:55 pm
sp_Permalink sp_Print sp_EditHistory

David,

On my pc, all the spaces are deleted. Can you provide a file with the problem?

BR,

Lionel

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
5
January 16, 2021 - 1:32 pm
sp_Permalink sp_Print

Thanks Lionel your support.

Pls refer attached again after executed the macro, some cells highlighted, for samples consequetive leading spaces,comma, still can not removed, so can not convert to value attribute for calculation. Or, may it be we are using Chinese Office 2019 version , some character codes net yet configured to remove by this Macro?

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
6
January 16, 2021 - 1:36 pm
sp_Permalink sp_Print

BTW , when you define the parameter what do your mean by Ligne?

Dim Ligne As Integer, cell As Range

Avatar
Purfleet
England
Member
Members


Trusted Members
Level 4
Forum Posts: 414
Member Since:
December 20, 2019
sp_UserOfflineSmall Offline
7
January 16, 2021 - 9:58 pm
sp_Permalink sp_Print

Slightly different take on it - might help with non numbers in chinese?

This Macro loops through each cell in a selectoin and checks if each character is a number - not sure of the Chinese ascii character set so it might need tweaking on this row If TestN >= 48 And TestN <= 57 = True Then

You must select a range for it to work

Sub NumbersOnly()

Dim n As Integer
Dim QtyOfN As Integer
Dim c As Range
Dim r As Range
Dim S As String
Dim TestN As Variant

Set r = Selection

For Each c In r
c.Activate
QtyOfN = Len(c)
If QtyOfN = 0 Then GoTo x
For n = 1 To QtyOfN

TestN = Asc(Mid(c, n, 1))

If TestN >= 48 And TestN <= 57 = True Then
S = S & Chr(TestN)
End If

Next n

ActiveCell = S + 0

S = ""
x:

Next c

End Sub

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
8
January 16, 2021 - 10:35 pm
sp_Permalink sp_Print

Thanks Purfleet, Lionel , this works out exactly and precisely remove all leading and trailing spaces in every cells.
My sincere thanks again, really treasure the macro skills and lessons derived from this forum

Avatar
Alan Elston
Out of here
Member
Members
Level 0
Forum Posts: 21
Member Since:
December 29, 2020
sp_UserOfflineSmall Offline
9
January 17, 2021 - 9:50 am
sp_Permalink sp_Print

Hi,

Just out of passing interest, I looked at the characters in the workbook with a function which  I have that lists all characters in strings.

It looks as though there are a lot of

 Chr(160)s (Non-breaking space )

and

 a few Chr(32)s ( space )

 

_.______________________________________________

 

Here  is another macro. It should remove all the spaces, Chr(160)s and Chr(32)s, in a selected range

 

Sub Trash160and32()  '   https://www.myonlinetraininghu.....s-in-cells

 Let Selection.Value = Evaluate("=If({1},SUBSTITUTE(SUBSTITUTE(" & Selection.Address & ", """ & Chr(32) & """, """"), """ & Chr(160) & """, """"))")

End Sub

_._______________________

Ref:

https://excelribbon.tips.net/T.....paces.html

https://excel.tips.net/T003037.....paces.html

 

_.____________________________________

 

Share ‘REMOVE-SPACE.xlsm’ : https://app.box.com/s/k15ug8bm.....edtcatefyl

Share ‘REMOVE-SPACE.xlsx’ :  https://app.box.com/s/b9u8m01l.....ju2l4hiaqf

 

Alan

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
10
January 18, 2021 - 3:46 pm
sp_Permalink sp_Print

Thanks Alan the altenative, they also worlk perfectly.

Avatar
Alan Elston
Out of here
Member
Members
Level 0
Forum Posts: 21
Member Since:
December 29, 2020
sp_UserOfflineSmall Offline
11
January 18, 2021 - 9:22 pm
sp_Permalink sp_Print sp_EditHistory

You are welcome. Thanks for confirming that the alternative works for you. That is good to know.

Alan

_.__________________________________________________

P.S.

If you have a very latest version of Microsoft Office, then this simplified code line may work also:

Selection.Value = Evaluate("=SUBSTITUTE(SUBSTITUTE(" & Selection.Address & ", """ & Chr(32) & """, """"), """ & Chr(160) & """, """")")

The above version is likely to work on Microsoft Office from approximately Microsoft Office 2016 and upwards

_.__

But I would recommend using my first alternative, since that should work in all Microsoft Office versions: The following  code line should work on both old and new Microsoft Office versions.

Selection.Value = Evaluate("=If({1},SUBSTITUTE(SUBSTITUTE(" & Selection.Address & ", """ & Chr(32) & """, """"), """ & Chr(160) & """, """"))")

(  The extra bit.._

 If({1},_________)

 _.. is one of a few known old  “tricks” that makes Evaluate("________") return an array of values.

We are beginning to notice that in newer Microsoft Office versions, these old “tricks” are no longer needed )

Ref: 

http://www.eileenslounge.com/v.....68#p276868

http://web.archive.org/web/202.....      )

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
12
January 20, 2021 - 10:18 am
sp_Permalink sp_Print

Thanks Alan, the supplement information.

Avatar
Philip Treacy
Admin
Level 10
Forum Posts: 1548
Member Since:
October 5, 2010
sp_UserOfflineSmall Offline
13
January 21, 2021 - 11:44 am
sp_Permalink sp_Print

Hi David,

Use Power Query.  The data looks like it's already been imported or copy/pasted - all numbers are text?  If you use PQ to bring this data into Excel in the first place, such problems can be dealt with easily.

Creating a table from your data, then opening in the PQ editor, just by converting the numeric columns to number type removes any non-printable chars and white space.

If you still need to do further clean up on text columns, use Transform -> Clean

Text.Clean - PowerQuery M | Microsoft Docs

Regards

Phil

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
14
January 22, 2021 - 10:19 am
sp_Permalink sp_Print

Thanks Philip,another brilliant alternative. Normally the data derive from System Report, so the PQ can come in to help transform data, make our Report much easier to handle.

Just eager to know can we use the PQ to alter the attribute of any column data convert to "Date", "Text", or join two columns or more data base on some specific criteria.

Avatar
Philip Treacy
Admin
Level 10
Forum Posts: 1548
Member Since:
October 5, 2010
sp_UserOfflineSmall Offline
15
January 23, 2021 - 3:53 pm
sp_Permalink sp_Print

Hi David,

If you mean can you convert columns to different data types in PQ, then yes, very easily.  

Likewise, joining columns together is simple in PQ - this is exactly the kind of thing it was built for.

Regards

Phil

Avatar
David_Ng
Member
Members
Level 0
Forum Posts: 306
Member Since:
December 5, 2016
sp_UserOfflineSmall Offline
16
January 26, 2021 - 10:17 am
sp_Permalink sp_Print

Thanks Philip, sorry late response,  will attempt.

sp_Feed
Go to top
Forum Timezone: Australia/Brisbane
Most Users Ever Online: 245
Currently Online: Ron Williams, Cindy Walawander
Guest(s) 11
Currently Browsing this Page:
1 Guest(s)
Top Posters:
SunnyKow: 1432
Anders Sehlstedt: 880
Purfleet: 414
Frans Visser: 346
David_Ng: 306
lea cohen: 237
Jessica Stewart: 219
A.Maurizio: 213
Aye Mu: 201
jaryszek: 183
Newest Members:
Clare Webber
David Jenssen
Dominic Brosnahan
Young You
Jennifer Owens
Mohamed Touahria
Sheila McCall
Nicholas Montano
John Babcock
QSolutions Group
Forum Stats:
Groups: 3
Forums: 24
Topics: 6524
Posts: 28549

 

Member Stats:
Guest Posters: 49
Members: 32803
Moderators: 2
Admins: 4
Administrators: Mynda Treacy, Philip Treacy, Catalin Bombea, FT
Moderators: Velouria, Riny van Eekelen
© Simple:Press —sp_Information

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • Excel Office Scripts
  • Excel PivotTables
  • Excel Shortcuts
  • Excel VBA
  • General Tips
  • Online Training
  • Outlook
  • Power Apps
  • Power Automate
  • Power BI
  • Power Pivot
  • Power Query
microsoft mvp logo
trustpilot excellent rating
Secured by Sucuri Badge
MyOnlineTrainingHub on YouTube Mynda Treacy on Linked In Mynda Treacy on Instagram Mynda Treacy on Twitter Mynda Treacy on Pinterest MyOnlineTrainingHub on Facebook

Sign up to our newsletter and join over 400,000
others who learn Excel and Power BI with us.

 

Company

  • About My Online Training Hub
  • Disclosure Statement
  • Frequently Asked Questions
  • Guarantee
  • Privacy Policy
  • Terms & Conditions
  • Testimonials
  • Become an Affiliate
  • Sponsor Our Newsletter

Support

  • Contact
  • Forum
  • Helpdesk - For Technical Issues

Copyright © 2023 · My Online Training Hub · All Rights Reserved. Microsoft and the Microsoft Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries. Product names, logos, brands, and other trademarks featured or referred to within this website are the property of their respective trademark holders.