Question

VB code to remove spaces in a string

Asked by: montrof

I need some code to remove any spaces in  a string.  I have a list of accounts in a column A and each cell has a bunch of numbers in it.
Example
Cell A1  100 00 0000 00
Cell A2   2222 2 222 22
So there is no pattern to the spaces, but I need something that go through each cell in column A and remove all the spaces.
So my results would look like this
Cell A1 10000000000
Cell A2 2222222222

Thanks for the help,
Montrof

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2004-01-23 at 14:33:20ID20861255
Tags

remove

,

spaces

,

string

,

vb

Topic

Microsoft Excel Spreadsheet Software

Participating Experts
5
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. An apostrophe in a cell A1 will not show up in the VBA ran…
    If I have '=a2 in cell A1 and then run the following code Sub test() dim sFormula as string sFormula = Range("a1").Formula End Sub sFormula will be set to =a2 how can sFormula set to '=a2 ??? Thanks
  2. =A1 in B1, =A2 in C1, =A3 in D1, ......
    Hi Experts, I want to put =A1 in B1, =A2 in C1, =A3 in D1, ......, =A99 in .... Any idea? Thank you in advance.
  3. Replace =(A1+A2+A3) with a formula that recogins…
    Hi I'd like to replace the following calculation with a calculation which knows which row its been entered into. For example: A B C D Row 1 1 2 3 =(A1+B1+C1) Row 2 1 2 3 =(...
  4. =FileName\Sheet\Cell is a Number, but =SUM(A2:A…
    Hi I have a spreadsheet which takes its information from a number of other spreadsheets, with it cells being populated in the following mannor: =FileName\Sheet\Cell this works and returns either the required 1 or a 0 At the end of the list I would like to have a standard t...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: shivsaPosted on 2004-01-23 at 14:41:10ID: 10188371

 

by: montrofPosted on 2004-01-23 at 14:45:02ID: 10188387

How do I tell the function to look at all the cells in column A?

 

by: montrofPosted on 2004-01-23 at 14:47:10ID: 10188402

Also, How would I make it so it does not delete dublicate characters?

 

by: byundtPosted on 2004-01-23 at 15:20:21ID: 10188594

Hi montrof,

Try it without a macro. Select your column, then use the Edit...Replace menu item. Enter a single space in the Find what field and nothing at all in the Replace with field. Click OK, and the job should be done.

Here's a macro that works on the selected range (could be an entire column):

Sub DeleteBlanks()
    Selection.Replace What:=" ", Replacement:="", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
End Sub

Cheers!

Brad

 

by: montrofPosted on 2004-01-23 at 15:56:40ID: 10188793

I tried find and replace early on and I was unsuccesful in getting it to work.

Thanks for the suggetion
Montrof

 

by: byundtPosted on 2004-01-23 at 16:04:05ID: 10188836

montrof,
Are the spaces really there in your strings? If you format the cell with a custom number format like ### ## #### (like a social security number) there will be spaces in the printout and screen display, but not in the value stored in the cell. Find and Replace won't get rid of them--you'll have to change the cell format instead.
Brad

 

by: heer2351Posted on 2004-01-23 at 16:16:11ID: 10188879

Try the substitute function:

=SUBSTITUTE(A1," ","")

Place it in column B for example, it will remove all spaces. You can then copy this column to column A by only pasting the values: Edit -> Paste Special -> Values

 

by: heer2351Posted on 2004-01-23 at 16:18:39ID: 10188889

Posted too soon.

I do agree with Brad that if find and replace does not work it might be the formatting. Although you state that the spaces are random, so that would rule out formatting.

 

by: montrofPosted on 2004-01-25 at 08:25:08ID: 10195699

There is no formating set to the column.  It is set to General.

 

by: montrofPosted on 2004-01-25 at 08:35:41ID: 10195757

I have no formatting on any of the cells.

 

by: montrofPosted on 2004-01-25 at 08:37:04ID: 10195766

The reason I would like to use a macro is that each month people will be dumping 1000s of account numbers into column a and then I need to make sure that there are no spaces in the account strings, so that i can upload them.

 

by: brettdjPosted on 2004-01-25 at 17:02:53ID: 10198082

I assume that your account numbers in Column A are values not formulas?

I tried Brad's code and it worked fine in Excel 2003 but it threw up an error in Excel 2000, but when I cut the Replace method down to three arguments as below it worked ok

Sub Rep()
    Dim MyRange As Range
    Set MyRange = Intersect(Columns("a:a"), ActiveSheet.UsedRange)
    MyRange.Replace What:=" ", Replacement:="", LookAt:=xlPart
End Sub

If this still doesn't work then this more complex RegExp sub may be worth a shot

Sub BlankDel()
    Dim Reg
    Dim MyRange As Range
    Dim Cel As Range
    Set MyRange = Intersect(Columns("a:a"), ActiveSheet.UsedRange)
    Set Reg = CreateObject("vbscript.regexp")
    Reg.Global = True
    For Each Cel In MyRange
        Reg.Pattern = "\s+"
        Cel.Value = Reg.Replace(Cel.Value, "")
    Next
End Sub

Cheers

Dave

 

by: montrofPosted on 2004-01-26 at 07:36:47ID: 10201168

I am getting an error when I try to run the macro that stops at the following line

Set Reg = CreateObject("vbscript.regexp")

The error is as follows;
Run time error '432'
File name or class name not found during Automation Operation

Thanks
Montrof

 

by: montrofPosted on 2004-01-26 at 08:09:26ID: 10201428

I found this macro posted and it seems to work
Sub RemoveSpaces()
 
  'Declare variables
  Dim ws As Worksheet
  Dim rng As Range
  Dim arr As Variant
  Dim r As Long
 
  'Rng refers to the used range in the first column
  'of the active sheet
  Set ws = ActiveSheet
  Set rng = ws.UsedRange.Columns(1)
 
  'Read the values of rng into array
  arr = rng.Value
 
  'Loop through all rows in the array
  For r = 1 To rng.Rows.Count
    'Remove spaces
    arr(r, 1) = WorksheetFunction.Substitute(arr(r, 1), " ", "")
  Next r
 
  'Write values back to sheet
  rng.Value = arr
 
  'Release object variables
  Set rng = Nothing
  Set ws = Nothing
 
End Sub


 

by: montrofPosted on 2004-01-26 at 08:31:53ID: 10201616

Actually this macro kind of works, here is the problem.

If account has leading zeros it deletes them and some of the accounts it makes them to the E power.

 

by: manthaneinPosted on 2004-02-19 at 19:09:35ID: 10409144

hello montrof,
I hope this will help you..   I created a simple macro to remove blanks. this is to ensure that the value will be considered as text not numbers


Sub removeBlanks()
Dim strHolder As String
Dim icount As Integer
Dim strChar As String
While ActiveCell.Value <> ""
    strHolder = ActiveCell.Value
    ActiveCell.Value = ""
    For icount = 1 To Len(strHolder)
        strChar = Mid(strHolder, icount, 1)
        If strChar <> " " Then
            ActiveCell.Value = ActiveCell.Value & strChar
           
        End If
    Next
    ActiveCell.Value = "=""" & ActiveCell.Value & """"
    ActiveCell.Offset(1, 0).Select
   
Wend
 ActiveCell.Offset(-1, 0).Select
Range(Selection, Selection.End(xlUp)).Select
Application.CutCopyMode = False
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
End Sub

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...