text manipulation

keith05281967

Board Regular
Joined
May 6, 2011
Messages
68
Greetings All,

I posted this question yesterday but failed to mention that i'm looking for a vba solution. I did get some great answers but they were in the form of worksheet functions =LEFT(A1,LEN(A1)-2)&REPT(" ",3-(LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))&RIGHT(A1,2)

I have cells with data like this: "Houston TX " or "Phoenix AZ " but occasionally it comes in like "AustinTX " with no spacing.

In order to pass the database test these cells should have at least 3 spaces between the city and the 2 digit state. I think the logic to make this work is to start from the far right of the cell, remove any trailing spaces, then move 2 spaces left so the focus is to the immediate left of the 2 digit TX state abbv. then going right to left count the number of spaces. If < 3 spaces then add 3 spaces.

It would loop thru a column of data doing this.

Can this be done in vba code?

Excel '07

thanks,
Keith
<!-- / message -->
 

Excel Facts

Round to nearest half hour?
Use =MROUND(A2,"0:30") to round to nearest half hour. Use =CEILING(A2,"0:30") to round to next half hour.
Maybe like this

Code:
Sub test()
With Range("A1")
    .Value = Evaluate("=LEFT(A1,LEN(A1)-2)&REPT("" "",3-(LEN(A1)-LEN(SUBSTITUTE(A1,"" "",""""))))&RIGHT(A1,2)")
End With
End Sub
 
Upvote 0
Assuming your data starts from A2...

Code:
Sub a()
Dim Last_Row As Long
Dim i As Long
Dim s As String

Application.ScreenUpdating = False

Last_Row = Range("A" & Rows.Count).End(xlUp).Row

For i = 2 To Last_Row
    s = Cells(i, 1).Value
    s = Trim(s)
    s = Left(s, Len(s) - 2) & "   " & Right(s, 2)
    Cells(i, 1).Value = s
Next i

Application.ScreenUpdating = True

End Sub
 
Upvote 0

Forum statistics

Threads
1,224,590
Messages
6,179,752
Members
452,940
Latest member
rootytrip

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top