Excel从string中提取第n个字

我想在vba中创build一个函数,从string中提取第一个第n个单词,看起来像这样

ExtractWords(affected_text,delimiter,number_of_words_to_extract)

我尝试了一个解决scheme,但它只提取前两个单词。

Function FirstWords(myStr As Variant, delimiter,words_to_extract) As Variant FirstWords = Left(myStr, InStr(InStr(1, myStr, delimiter) + 1, myStr, delimiter, vbTextCompare) - 1) End Function 

有任何想法吗? 谢谢

使用Split()函数。 它返回String数组,使用您指定的单词的分隔符和限制进行分割。

 Dim Result As Variant Result = Split("Alice,Bob,Chuck,Dave", ",") 'Result: {"Alice,"Bob","Chuck","Dave"} Result = Split("Alice,Bob,Chuck,Dave", ",", 2) 'Result: {"Alice,"Bob"} 

@ Taosique使用Split的答案非常好,但是如果你想把结果作为string返回,你可以这样做:

 Function FirstWords(myStr As String, delimiter As String, words_to_extract As Long) As Variant Dim i As Long, k As Long For i = 1 To Len(myStr) If Mid(myStr, i, 1) = delimiter Then k = k + 1 If k = words_to_extract Then FirstWords = Mid(myStr, 1, i) Exit Function End If End If Next I 'if you get to here -- trouble 'unless the delimiter count is words_to_extract - 1 If k = words_to_extract - 1 Then FirstWords = myStr Else FirstWords = CVErr(xlErrValue) End If End Function Sub test() Debug.Print FirstWords("This is a test. I hope it works", " ", 4) Debug.Print FirstWords("This is a test. I hope it works", " ", 10) End Sub 

运行test ,首先显示string“This is a test”。 然后打印一个错误条件。

与上面相同的效果可以通过首先使用Split拆分string然后使用Join重新Join 。 一个细微的差异是行为,如果有less于words_to_extract字。 Split then Join方法将返回整个string。 上面的代码将其视为错误条件,如果用作UDF工作表函数,将显示#VALUE! 在包含它的任何单元格中。