我正在尝试在Excel中使用公式用逗号分隔单元格中的一堆单词。如果单元格中有超过5个单词,我只想获得前5个单词。要获取单元格中的前五个单词并用逗号分隔,我使用它:
=SUBSTITUTE(LEFT(A1,FIND("^",SUBSTITUTE(A1," ","^",5))-1), " ", ", ")
这很好用。但是这个问题,因为这里的数字5,如果我的单元格包含少于5个单词,我会收到一个错误。我试图用这个代替5:
LEN(TRIM(A1))-LEN(SUBSTITUTE(A1," ",""))+1
所以我的功能变成了这个:
=SUBSTITUTE(LEFT(A1,FIND("^",SUBSTITUTE(A1," ","^",LEN(TRIM(A1))-LEN(SUBSTITUTE(A1," ",""))+1))-1), " ", ", ")
但这不起作用,它给了我一个错误。知道我怎么能这样做吗?
另外我想忽略第一个字,如果它的第一个字符是“ - ”(没有引号),只是从第二个字开始。换句话说,我想要这样的事情:
我非常爱我的生活应该回归我,爱,我的,生活,非常的 - 我非常爱我的生活应该回归我,爱,我的,生活,非常(“ - ”被忽略“) 我爱我应该回归我,爱,我的
提前感谢您提供任何帮助
答案 0 :(得分:2)
这是一种有点不同的方法。除了“不到5个”的问题,它还处理“最后没有空格的5个字”问题:
=LEFT(A1,FIND("^",SUBSTITUTE(A1 & "^"," ","^",5))-1)
编辑1:我刚注意到关于领先“ - ”的部分。我的添加不是很优雅,但它处理它,以及TRIMS
任何尾随空格:
=TRIM(LEFT(IF(LEFT(A1,2)="- ",MID(A1,3,999),A1),FIND("^",SUBSTITUTE(IF(LEFT(A1,2)="- ",MID(A1,3,999),A1) & "^"," ","^",5))-1))
编辑2:哦,是的,逗号:
=SUBSTITUTE(TRIM(LEFT(IF(LEFT(A1,2)="- ",MID(A1,3,999),A1),FIND("^",SUBSTITUTE(IF(LEFT(A1,2)="- ",MID(A1,3,999),A1) & "^"," ","^",5))-1))," ",",")
答案 1 :(得分:2)
试试这个:
= TRIM(左侧(替换(替换(替换(替换(A1," - ","")),"",&# 34;,"),",",REPT("",99),5),99))
答案 2 :(得分:1)
即使短划线后面有没有空格,或者文字中有额外空格,这也会有效。我经常发现输入不是 clean 。
=SUBSTITUTE(LEFT(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"-","",1)),
" ","*",5),IFERROR(FIND("*",SUBSTITUTE(TRIM(SUBSTITUTE(A1,"-","",1)),
" ","*",5))-1,999))," ",",")
编辑:在对István发表评论之后,我也让它完美无瑕。
=SUBSTITUTE(LEFT(SUBSTITUTE(TRIM(SUBSTITUTE(LEFT(TRIM(A1),1),"-"," ",1)
&MID(TRIM(A1),2,999))," ","*",5),IFERROR(FIND("*",SUBSTITUTE(
TRIM(SUBSTITUTE(LEFT(TRIM(A1),1),"-","",1)&MID(TRIM(A1),2,999))," ","*",5))-1,999))," ",",")
但我认为他更优雅。
答案 3 :(得分:0)
试试这个:
=SUBSTITUTE(LEFT(SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"- ","",1))&" "," ",", "),", ","|",MIN(LEN(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"- ","",1))&" "," ",", "))-LEN(SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"- ","",1))&" "," ",", ")," ","")),5)),FIND("|",SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"- ","",1))&" "," ",", "),", ","|",MIN(LEN(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"- ","",1))&" "," ",", "))-LEN(SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(A1,"- ","",1))&" "," ",", ")," ","")),5)))-1),",,",",")
该公式采用以下步骤:
如果您愿意考虑使用VBA解决方案,则可以使用用户定义的函数替换此复杂表达式:
Function words5(InputString As String) As String
Dim wordArray As Variant
wordArray = Split(Trim(Replace(InputString, _ 'remove "-", put words into array
"-", "", , 1)), " ")
ReDim Preserve wordArray(LBound(wordArray) To _ 'drop all but the first 5 words
WorksheetFunction.Min(UBound(wordArray), 5 - 1))
words5 = Replace(Join(wordArray, ", "), ",,", ",") 'rejoin the words with ", "
End Function 'separator
使用此代码的另一方面是它与工作表公式相比的可维护性,如果不访问组合到单个表达式中的原始构建块,则无法理解或安全地更改。
代码必须安装在使用它的工作簿中,或者安装在标准的Personal.xlsb工作簿或插件工作簿中。
要使用该功能,请将其复制并粘贴到标准模块中,该模块可以通过VBA编辑器插入到工作簿中。您可以使用功能区的“开发人员”选项卡上的Visual Basic
按钮打开编辑器。
答案 4 :(得分:0)
=SUBSTITUTE(TRIM(LEFT(SUBSTITUTE(TRIM(SUBSTITUTE(A1&" ","- ",""))," ",REPT(" ",99)),99*5))," ",",")