简体   繁体   中英

How to extract characters in a string within a cell using in excel formula

Here is the sample string in A1 cell:

13TR@1X1127, 13TR@3X2500, @1X1373

I want to extract "n" in the pattern @nX, where n can be up to 3 digits in length, and then sum the value in Cell B1 .

Example:

13TR@1X1127, 13TR@3X2500, @1X1373

extract value: 1, 3, 1

And add in B1: 5

I have written the formula up to formula up to 2nd string but it seems it will be very long.

=MID(A1,FIND("@",A1,1)+1,FIND("X",A1,FIND("@",A1,1))-FIND("@",A1,1)-1)+IFERROR(MID(A1,FIND("@",A1,FIND("X",A1,FIND("@",A1,1)))+1,FIND("X",A1,FIND("@",A1,FIND("X",A1,FIND("@",A1,1))))-FIND("@",A1,FIND("X",A1,FIND("@",A1,1)))-1),0)

Is there a way to simplify the formula so it will sum up to Nth String?

You could use a VBA function like this:

( Edited to allow for multiple digits between @ and X .)

Function SumNums(strIn As String) As Integer
    Dim p1 As Integer, p2 As Integer
    p1 = InStr(strIn, "@")
    Do While p1 > 0
        p2 = InStr(p1, strIn, "X") - 1
        SumNums = SumNums + Val(Mid(strIn, p1 + 1, p2 - p1))
        p1 = InStr(p1 + 1, strIn, "@")
    Loop
End Function

Also this way, the "number of occurrences" doesn't have to be decided in advance.

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