尝试这个:
=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),",,",",")
该公式通过以下步骤起作用:
- 删除任何前导的破折号空间
- 修剪任何前导或尾随空格
- 插入逗号空格代替空格并添加尾随逗号空格
- 计算 5 和字符串中的单词数中的较小者
- 输入“|” 如果字符串少于五个单词,则代替第五个逗号空格或尾随逗号空格
- 确定“|”的位置
- 去掉“|” 以及它右边的所有字符
- 删除由于初始字符串中的任何单个嵌入逗号而导致的任何双引号
如果您愿意考虑 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
功能区的“开发人员”选项卡上的按钮打开编辑器。