Solved

Macro to remove spaces

Posted on 2016-07-14
14
61 Views
Last Modified: 2016-07-14
Hello,
can you please help with an excel vba to remove spaces and format properly.
Example
COMPANY
STREET
City,   Q C   JOE 1E0

Should be
COMPANY      
STREET      
City, QC JOE1E0      ---- (City COMMA SPACE PROVINCE SPACE POSTALCODE)

Please see attached sample.
Any help is appreciated.
sample2.xlsx
0
Comment
Question by:Wass_QA
  • 7
  • 4
  • 3
14 Comments
 
LVL 28

Expert Comment

by:Subodh Tiwari (Neeraj)
ID: 41711084
Try this....

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

Open in new window

0
 

Author Comment

by:Wass_QA
ID: 41711103
Hi Sudodh,
Thank you very muc,

Is it possible to add an if

if Adjacent cell in Column B = "Add to File"
then  do
Columns("A:A").Replace What:="  ", Replacement:="", LookAt:=xlPart, _
    SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
    ReplaceFormat:=False

Thanks again,
0
 
LVL 48

Expert Comment

by:Rgonzo1971
ID: 41711121
Hi,

pls try

Sub macro()

For Each c In Range(Range("A2"), Range("A" & Rows.Count).End(xlUp))
strNewAddress = ""
    If c.Offset(, 1) = "Add to File" Then
        aAddress = Split(c, ",")
        For idx = 1 To Len(aAddress(1))
            strLetter = Mid(aAddress(1), idx, 1)
            If strLetter <> " " Then
                strNewAddress = strNewAddress & strLetter
            End If
        Next
        strNewAddress = " " & Left(strNewAddress, 2) & " " & Right(strNewAddress, Len(strNewAddress) - 3)
        aAddress(1) = strNewAddress
        c.Value = Join(aAddress, ",")
    End If
Next
End Sub

Open in new window

Regards
0
 
LVL 28

Expert Comment

by:Subodh Tiwari (Neeraj)
ID: 41711141
Please try this......
Sub RemoveSpaces()
Dim lr As Long
Dim rng As Range, cell As Range
lr = Cells(Rows.Count, 2).End(xlUp).Row
On Error Resume Next
With ActiveSheet.Rows(1)
   .AutoFilter field:=2, Criteria1:="Add to File"
   If Range("B1:B" & lr).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
      Set rng = Range("A1:A" & lr).SpecialCells(xlCellTypeVisible)
      For Each cell In rng
         cell = WorksheetFunction.Trim(cell.Value)
      Next cell
   End If
   .AutoFilter
End With
End Sub

Open in new window

0
 
LVL 28

Expert Comment

by:Subodh Tiwari (Neeraj)
ID: 41711156
Please try this tweaked code.......
Sub RemoveSpaces()
Dim lr As Long
Dim rng As Range, cell As Range
lr = Cells(Rows.Count, 2).End(xlUp).Row
On Error Resume Next
With ActiveSheet.Rows(1)
   .AutoFilter field:=2, Criteria1:="Add to File"
   If Range("B1:B" & lr).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
      Set rng = Range("A1:A" & lr).SpecialCells(xlCellTypeVisible)
      For Each cell In rng
         cell = WorksheetFunction.Trim(cell.Value)
         cell = WorksheetFunction.Replace(cell.Value, InStrRev(cell.Value, " "), 1, "")
      Next cell
   End If
   .AutoFilter
End With
End Sub

Open in new window

0
 
LVL 48

Expert Comment

by:Rgonzo1971
ID: 41711164
pls try

Sub macro()

For Each c In Range(Range("A2"), Range("A" & Rows.Count).End(xlUp))
strNewAddress = ""
    If c.Offset(, 1) = "Add to File" Then
        aAddress = Split(c, ",")
        strNewAddress = Replace(aAddress(1), " ", "")
        strNewAddress = " " & Left(strNewAddress, 2) & " " & Right(strNewAddress, Len(strNewAddress) - 3)
        aAddress(1) = strNewAddress
        c.Value = Join(aAddress, ",")
    End If
Next
End Sub

Open in new window

0
 

Author Comment

by:Wass_QA
ID: 41711178
Thank you ,
Rgonzo,

your code is trimming the left letter of the postal code.
Example
ANGEGARDIEN, QC JOE1E0
becomes
ANGEGARDIEN, QC OE1E0

Subodh
Your code is combining province with postalcode
CONTRECOEUR, QC  JOL 1CO
Becomes
CONTRECOEUR, QCJOL 1CO
0
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 28

Expert Comment

by:Subodh Tiwari (Neeraj)
ID: 41711183
Did you try my latest tweaked code?
It converts CONTRECOEUR, QC  JOL 1CO into CONTRECOEUR, QC  JOL1CO
0
 

Author Comment

by:Wass_QA
ID: 41711197
Hi Sudobh,
I just tried the tweaked code

ROUYNNORANDA,   QC   J9X5E4
Becomes
ROUYNNORANDA, QCJ9X5E4
0
 
LVL 28

Expert Comment

by:Subodh Tiwari (Neeraj)
ID: 41711227
Okay give it a try...

Sub RemoveSpaces()
Dim lr As Long
Dim rng As Range, cell As Range
lr = Cells(Rows.Count, 2).End(xlUp).Row
On Error Resume Next
With ActiveSheet.Rows(1)
   .AutoFilter field:=2, Criteria1:="Add to File"
   If Range("B1:B" & lr).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
      Set rng = Range("A1:A" & lr).SpecialCells(xlCellTypeVisible)
      For Each cell In rng
         If cell <> "" Then
            cell = Replace(cell.Value, Chr(160), " ")
            Do While InStr(cell.Value, "  ") > 0
               cell = Replace(cell.Value, "  ", " ")
            Loop

            If InStr(Right(cell.Value, 6), " ") <> 0 Then
               cell = WorksheetFunction.Replace(cell.Value, InStrRev(cell.Value, " "), 1, "")
            End If
         End If
      Next cell
   End If
   .AutoFilter
End With
End Sub

Open in new window

0
 
LVL 28

Accepted Solution

by:
Subodh Tiwari (Neeraj) earned 250 total points
ID: 41711240
I have tweaked the code again. :)

Please try the code given below.....
Sub RemoveSpaces()
Dim lr As Long
Dim rng As Range, cell As Range
lr = Cells(Rows.Count, 2).End(xlUp).Row
On Error Resume Next
With ActiveSheet.Rows(1)
   .AutoFilter field:=2, Criteria1:="Add to File"
   If Range("B1:B" & lr).SpecialCells(xlCellTypeVisible).Cells.Count > 1 Then
      Set rng = Range("A1:A" & lr).SpecialCells(xlCellTypeVisible)
      For Each cell In rng
         If cell <> "" Then
            cell = Replace(cell.Value, Chr(160), " ")
            Do While InStr(cell.Value, "  ") > 0
               cell = Replace(cell.Value, "  ", " ")
            Loop
            cell = WorksheetFunction.Trim(cell.Value)
            If InStr(Right(cell.Value, 6), " ") <> 0 Then
               cell = WorksheetFunction.Replace(cell.Value, InStrRev(cell.Value, " "), 1, "")
            End If
         End If
      Next cell
   End If
   .AutoFilter
End With
End Sub

Open in new window

0
 
LVL 48

Assisted Solution

by:Rgonzo1971
Rgonzo1971 earned 250 total points
ID: 41711350
then
trySub macro()

For Each c In Range(Range("A2"), Range("A" & Rows.Count).End(xlUp))
strNewAddress = ""
    If c.Offset(, 1) = "Add to File" Then
        aAddress = Split(c, ",")
        For idx = 1 To Len(aAddress(1))
            strLetter = Mid(aAddress(1), idx, 1)
            If strLetter <> " " Then
                strNewAddress = strNewAddress & strLetter
            End If
        Next
        strNewAddress = " " & Left(strNewAddress, 2) & " " & Right(strNewAddress, Len(strNewAddress) - 2)
        aAddress(1) = strNewAddress
        c.Value = Join(aAddress, ",")
    End If
Next
End Sub

Open in new window

0
 

Author Closing Comment

by:Wass_QA
ID: 41711424
Thank you very much guys.
Both worked.
0
 
LVL 28

Expert Comment

by:Subodh Tiwari (Neeraj)
ID: 41711671
You're welcome. Glad to help.
0

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

PaperPort has a feature called the "Send To Bar". It provides a convenient, drag-and-drop interface for using other installed software, such as Microsoft Office. However, this article shows that the latest Office 2016 apps (installed with an Office …
In this article we discuss how to recover the missing Outlook 2011 for Mac data like Emails and Contacts manually.
The viewer will learn how to use a discrete random variable to simulate the return on an investment over a period of years, create a Monte Carlo simulation using the discrete random variable, and create a graph to represent the possible returns over…
The viewer will learn how to  create a slide that will launch other presentations in Microsoft PowerPoint. In the finished slide, each item launches a new PowerPoint presentation and when each is finished it automatically comes back to this slide: …

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now