简体   繁体   中英

Excel formula to extract text from mid

Here, I am extracting middle name from text using below formula

=MID(I2, SEARCH("-",I2) + 1, SEARCH("-",I2,SEARCH("-",I2)+1) - SEARCH("-",I2) - 1)

So from name "Goapta-Saaririka-Aaasshok", I can pull the "Saaririka" but I have a problem if I have only first name and middle name and not last name. Above formula is not working to pull the middle name from "Basrsaaggade-Aamimit"

Please assist as how can I pull Mid name even if there is no last name.

Test for the number of dashes. For data in column A :

=IF(LEN(A1)-LEN(SUBSTITUTE(A1,"-",""))=2,MID(A1, SEARCH("-",A1) + 1, SEARCH("-",A1,SEARCH("-",A1)+1) - SEARCH("-",A1) - 1),MID(A1,FIND("-",A1)+1,99))

在此处输入图像描述

If there are 2 dashes, take the middle string
if there is 1 dash, take the last string.

(with Excel 365 this can be made much shorter)

You can try to split your string on each hyphen:

在此处输入图像描述

Formula in B1 :

=FILTERXML("<t><s>"&SUBSTITUTE(A1,"-","</s><s>")&"</s></t>","//s[2]")
  • //s[2] - Always return the second node from our resulting array.

No need to test for the number of dashes.

Assuming your data starts in A1. Put this in B1: =TRIM(MID(SUBSTITUTE(A1,"-",REPT(" ",255)),256,256))

Drag down.

It replaces every dash with 255 spaces, then it chops 256 chars from 256 chars in which guarantees the inclusion of the second element, then it trims off the excess spaces.

If you wish to do this with a UDF in VBA instead you can split the string into an array using "-" as the delimeter and take the second element.

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