如何检测单元格中的特定字符串文本并将其删除?

时间:2017-02-20 16:11:28

标签: excel excel-formula excel-2016

我有一个A2格式的位置列表:[城市州],其中城市或州可以由两个以上的单词组成。所有这些都在一个单元格中。我有数千的总数据。现在,我还有一个列表。我需要做的是从A2中删除状态,并在那里留下剩下的字符串。因此只留下城市。我需要帮助,因为数据是数百万,我有一个大约30K城市的列表。

1 个答案:

答案 0 :(得分:1)

您可以在单元格旁边创建2个单元格,其中包含一个用于城市的数据和一个用于状态的数据。输入公式并自动填充。

提取城市的公式

=left(A1,find(" ",A1,1)-1)

提取状态的公式

=right(A1,len(A1)-find(" ",A1,1))

这些公式将文本放在第一个空格的左侧,将文本放在第一个空格的右侧。如果城市有空间,您将遇到问题,例如“纽约”,但很难解决这个问题。

另一种方法是使用VBA代码遍历所有单元格并在单元格上运行相同的代码并从该单元格中删除State并将State放在不同的单元格中。这是一个更复杂的选择。

解决有两个字问题的城市

我假设Sates是美国州,因此我创建了包含2个单词的所有美国州的字符串

[新罕布什尔] [新泽西] [新墨西哥] [纽约] [北卡罗来纳] [北达科他州] [罗德岛] [南卡罗来纳州] [南达科他州] [西弗吉尼亚州]

如果将这些状态粘贴到单元格B1中,则可以使用单元格B3中的公式来检查A3的内容并提取城市。

=IF(ISNUMBER(FIND("[" & RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-1-LEN(SUBSTITUTE(A3," ",""))))) & "]",$B$1,1)),LEFT(A3,FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-1-LEN(SUBSTITUTE(A3," ",""))))-1),LEFT(A3,FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-LEN(SUBSTITUTE(A3," ",""))))-1))

然后将以下公式粘贴到单元格C3中以检查A3的内容并提取状态。

=IF(ISNUMBER(FIND("[" & RIGHT(F9,LEN(F9)-FIND("☃",SUBSTITUTE(F9," ","☃",LEN(F9)-1-LEN(SUBSTITUTE(F9," ",""))))) & "]",$B$1,1)),RIGHT(F9,LEN(F9)-FIND("☃",SUBSTITUTE(F9," ","☃",LEN(F9)-1-LEN(SUBSTITUTE(F9," ",""))))),RIGHT(F9,LEN(F9)-FIND("☃",SUBSTITUTE(F9," ","☃",LEN(F9)-LEN(SUBSTITUTE(F9," ",""))))))

处理3个字的国家的公式

公式变得非常长,但它所做的只是检查匹配,从末尾开始有3个空格的分割,然后是2个空格,如果找不到分裂在1个空格的状态。

提取城市

=IF(ISNUMBER(FIND("["&RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-2-LEN(SUBSTITUTE(A3," ","")))))&"]",$B$1,1)),LEFT(A3,FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-2-LEN(SUBSTITUTE(A3," ",""))))-1),IF(ISNUMBER(FIND("["&RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-1-LEN(SUBSTITUTE(A3," ","")))))&"]",$B$1,1)),LEFT(A3,FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-1-LEN(SUBSTITUTE(A3," ",""))))-1),LEFT(A3,FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-LEN(SUBSTITUTE(A3," ",""))))-1)))

提取州

=IF(ISNUMBER(FIND("["&RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-2-LEN(SUBSTITUTE(A3," ","")))))&"]",$B$1,1)),RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-2-LEN(SUBSTITUTE(A3," ",""))))),IF(ISNUMBER(FIND("["&RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-1-LEN(SUBSTITUTE(A3," ","")))))&"]",$B$1,1)),RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-1-LEN(SUBSTITUTE(A3," ",""))))),RIGHT(A3,LEN(A3)-FIND("☃",SUBSTITUTE(A3," ","☃",LEN(A3)-LEN(SUBSTITUTE(A3," ","")))))))

工作原理 该公式通过从最后一个空格中取出一个来查找倒数第二个空格(感谢用户m4573r获取最后一个空格公式)。然后它将最后一个空格的所有内容都加上,添加“[]”括号并将其与B1中的状态列表文本进行对比。如果它存在,那么它使用该点的倒数第二个空格将文本切成两半并从左侧返回City或从右侧返回State。