简体   繁体   中英

Excel 2016 - Split String of Random Text and Numbers to Separate Columns?

Here's an interesting one that I haven't been able to find an answer for yet.

I have an exported CSV file from a Python scraper that grabs MLB daily score results. The only problem I'm having is the output creates a string that looks like this for the day in cell A1:

Washington3FinalPhiladelphia1Washington7Final (10)Philadelphia6Houston5FinalDetroit4LA Dodgers1FinalCincinnati3Oakland3FinalBaltimore2Cleveland2FinalTampa Bay0Toronto2FinalBoston7Miami5FinalNY Mets3Milwaukee0FinalChi Cubs3NY Yankees5FinalMinnesota10Chi White Sox3FinalKansas City6Pittsburgh5FinalSt. Louis11Arizona6FinalColorado3Texas0FinalLA Angels1San Diego2FinalSeattle1Atlanta4FinalSan Francisco1

So just looking at the first bit, ideally what I like is a VBA script or function to separate each piece of data into their own columns so that I can manipulate the data easier from there. So I'd like to have an output that looks something like:

Washington | 3 | Final | Philadelphia | 1 | Washington | 7 | Final (10) | Philadelphia | 6 | etc....

Notice when a game goes into extra innings, it wraps the number of innings in brackets. I would also have a list of these daily score data in the subsequent rows beneath this one, so a loop through the entire worksheet would be ideal.

Any ideas at all? Thanks a lot!

You can use Regular Expressions for that.

And replace the following 2 patterns:

So the following should work for your string.

Option Explicit

Public Sub SplitTest()
    Dim SplitString As String
    SplitString = SplitCaps(Range("A1").Value)

    Debug.Print SplitString 'show splitstring in intermediate window

    'split into array and output into cell
    Dim SlitArray() As String
    SlitArray = Split(SplitString, "|")
    Range("B1").Resize(1, UBound(SlitArray) + 1).Value = SlitArray
End Sub

Public Function SplitCaps(InputString As String) As String
    Dim objRegex As Object
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
        .Global = True
        .Pattern = "([a-z]|[0-9]|\))([A-Z])" 'https://regex101.com/r/b9rdEH/1
        SplitCaps = .Replace(InputString, "$1|$2")

        .Pattern = "([a-z])([0-9])" 'https://regex101.com/r/rYtU1Z/1
        SplitCaps = .Replace(SplitCaps, "$1|$2")
    End With
End Function

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