简体   繁体   中英

Excel Macro Unable to Separate String Address

Software: MS Excel 2016


Update 1

Please note there can be any number of digits before West, ie

123124234234West18th Street

2West 14th Avenue

12324West

Please assist with general solution



Original Question

There is address, 31West 52nd Street I am trying to split the 31 and West so output will be

31 West 52nd Street

Tried this Macro statement but it won't work, please guide

Selection.Replace What:="?@West ", Replacement:=" West " _ , LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat _ :=False, ReplaceFormat:=False

This is a sample of code, that would check for the first few chars. If they are digits, if would split them with a space from the rest:

Option Explicit

Public Sub TestMe()

    Debug.Print fnStrStripMyNumber("31West  52nd Street")
    Debug.Print fnStrStripMyNumber("123Vityata Shampion")

End Sub

Public Function fnStrStripMyNumber(strStr As String) As String

    Dim lngCountDigits  As Long
    Dim lngCounter      As Long

    strStr = Trim(strStr)

    For lngCounter = 1 To Len(strStr)
        If IsNumeric(Mid(strStr, lngCounter, 1)) Then
            lngCountDigits = lngCountDigits + 1
        Else
            Exit For
        End If
    Next lngCounter

    strStr = Left(strStr, lngCountDigits) & " " & Right(strStr, Len(strStr) - lngCountDigits)
    fnStrStripMyNumber = Trim(strStr)

End Function

Thus, from input:

"31West  52nd Street"
"123Vityata Shampion"

We get output:

31 West  52nd Street
123 Vityata Shampion

You can try this excel formula as well,

=LEFT(A1,FIND("West",A1)-1)&" "&RIGHT(A1,LEN(A1)-FIND("West",A1)+1)

在此处输入图片说明

Or if you want a macro only,

Sub rep()
Range("B1") = Replace(Range("A1"), "West", " West")
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM