• 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
    • Password Reset
  • Blog
  • Excel Webinars
  • Excel Forum
    • Register as Forum Member
You are here: Home
Lost password?
sp_Search
Advanced Search
Advanced Search
Forum Scope




Match



Forum Options



Minimum search word length is 3 characters - maximum search word length is 84 characters
sp_Search

Please confirm you want to mark all posts read

Mark all topics read

sp_MobileMenu Actions
Actions
sp_LogInOut
Log In
sp_Search

Search Forums

sp_RankInfo
Ranks Information
Avatar

New/Updated Topics

General Excel Questions & Answers

  Calculate occurrences of max value by hour

  Lookup in a 3 Dimentional Table

  Amortization schedule with changing interest rate

  Exact Match searching, NOT partial.

  Data Validation with unique values

Dashboards & Charts

  Connecting 2 separate pivot charts or data sets to calculate…

VBA & Macros

  IF and Max Formula through VBA

  VBA to Have Template file remain Open after Copy is Saved &a…

Power Query

  Using Table.ReplaceValue with Text.Combine to do an in place…

  Removing columns in Power BI source file

  How to add a new query for each cell of a column

  Creating a new table from other data sources

  Converting Values from positive to Negative in Power Query

  Running total in power query

Xtreme Pivot Tables

  Structuring data to drive pivot tables.

Select Forum

  Rules and Guides

Forum Rules and Guides

  Public Forums - For Registered Users

General Excel Questions & Answers

Dashboards & Charts

VBA & Macros

Power Query

Power Pivot

  Course Members Only

Excel Dashboards

Power Query

Power Pivot

Xtreme Pivot Tables

Excel for Decision Making

Excel for Finance

Power BI

Excel

Word

Outlook

Excel Expert

Excel for Customer Service Professionals

Excel Analysis Toolpak

Excel Tables

Excel for Operations Management

Financial Modelling

Advanced Excel Formulas

Pivot Tables Quick Start

ForumsVBA & Macros
sp_TopicIcon
Macro remove leading and trailing spaces in cells
Avatar
David_Ng
Posts: 306
Level 0
January 15, 2021 - 9:59 am

1

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
Posts: 114
Level 0
January 15, 2021 - 3:16 pm

2

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
Posts: 306
Level 0
January 15, 2021 - 4:41 pm

3

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

Avatar
Lionel Baijot
Posts: 114
Level 0
January 15, 2021 - 9:55 pm

4

David,

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

BR,

Lionel

Avatar
David_Ng
Posts: 306
Level 0
January 16, 2021 - 1:32 pm

5

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
Posts: 306
Level 0
January 16, 2021 - 1:36 pm

6

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

Dim Ligne As Integer, cell As Range

Avatar
Purfleet
England
Posts: 412

Level 4
January 16, 2021 - 9:58 pm

7

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
Posts: 306
Level 0
January 16, 2021 - 10:35 pm

8

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
Posts: 21
Level 0
January 17, 2021 - 9:50 am

9

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
Posts: 306
Level 0
January 18, 2021 - 3:46 pm

10

Thanks Alan the altenative, they also worlk perfectly.

Avatar
Alan Elston
Out of here
Posts: 21
Level 0
January 18, 2021 - 9:22 pm

11

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
Posts: 306
Level 0
January 20, 2021 - 10:18 am

12

Thanks Alan, the supplement information.

Avatar
Philip Treacy
Posts: 1518
Level 10
January 21, 2021 - 11:44 am

13

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
Posts: 306
Level 0
January 22, 2021 - 10:19 am

14

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
Posts: 1518
Level 10
January 23, 2021 - 3:53 pm

15

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
Posts: 306
Level 0
January 26, 2021 - 10:17 am

16

Thanks Philip, sorry late response,  will attempt.

Forum Timezone:
Australia/Brisbane
Most Users Ever Online: 245
Currently Online: andria young, Bruce Tang Nian
Guest(s) 9
Currently Browsing this Page:
1 Guest(s)

Devices in use: Desktop (8), Phone (3)

Forum Stats:
Groups: 3
Forums: 24
Topics: 6222
Posts: 27293
Member Stats:
Guest Posters: 49
Members: 31918
Moderators: 3
Admins: 4
© Simple:Press

Sidebar

Blog Categories

  • Excel
  • Excel Charts
  • Excel Dashboard
  • Excel Formulas
  • 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
 

Company

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

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.