?
Solved

Macro to remove spaces

Posted on 2016-07-14
14
Medium Priority
?
93 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:W.E.B
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 7
  • 4
  • 3
14 Comments
 
LVL 32

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:W.E.B
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 52

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
Learn Veeam advantages over legacy backup

Every day, more and more legacy backup customers switch to Veeam. Technologies designed for the client-server era cannot restore any IT service running in the hybrid cloud within seconds. Learn top Veeam advantages over legacy backup and get Veeam for the price of your renewal

 
LVL 32

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 32

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 52

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:W.E.B
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
 
LVL 32

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:W.E.B
ID: 41711197
Hi Sudobh,
I just tried the tweaked code

ROUYNNORANDA,   QC   J9X5E4
Becomes
ROUYNNORANDA, QCJ9X5E4
0
 
LVL 32

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 32

Accepted Solution

by:
Subodh Tiwari (Neeraj) earned 1000 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 52

Assisted Solution

by:Rgonzo1971
Rgonzo1971 earned 1000 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:W.E.B
ID: 41711424
Thank you very much guys.
Both worked.
0
 
LVL 32

Expert Comment

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

Featured Post

Office 365 Training for IT Pros

Learn how to provision tenants, synchronize on-premise Active Directory, implement Single Sign-On, customize Office deployment, and protect your organization with eDiscovery and DLP policies.  Only from Platform Scholar.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

You need to know the location of the Office templates folder, so that when you create new templates, they are saved to that location, and thus are available for selection when creating new documents.  The steps to find the Templates folder path are …
This article describes how you can use Custom Document Properties to store settings and other information in your workbook so that they will be available the next time you open the workbook.
This Micro Tutorial will demonstrate how to use longer labels with horizontal bar charts instead of the vertical column chart.
Many functions in Excel can make decisions. The most simple of these is the IF function: it returns a value depending on whether a condition you describe is true or false. Once you get the hang of using the IF function, you will find it easier to us…

719 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