获得第n个词或最后一个词如果apporopriate

我正在使用一小段代码来从一个单元格中取出名称,并将它们分离为单独的单元格。 名字的数量差别很大,因此我需要尽可能地自动化。

我正在使用下面的macros:

Function Get_Word(text_string As String, nth_word) As String Dim lWordCount As Long With Application.WorksheetFunction lWordCount = Len(text_string) - Len(.Substitute(text_string, " ", "")) + 1 If IsNumeric(nth_word) Then nth_word = nth_word - 1 Get_Word = Mid(Mid(Mid(.Substitute(text_string, " ", "^", nth_word), 1, 256), _ .Find("^", .Substitute(text_string, " ", "^", nth_word)), 256), 2, _ .Find(" ", Mid(Mid(.Substitute(text_string, " ", "^", nth_word), 1, 256), _ .Find("^", .Substitute(text_string, " ", "^", nth_word)), 256)) - 2) ElseIf nth_word = "First" Then Get_Word = Left(text_string, .Find(" ", text_string) - 1) ElseIf nth_word = "Last" Then Get_Word = Mid(.Substitute(text_string, " ", "^", Len(text_string) - _ Len(.Substitute(text_string, " ", ""))), .Find("^", .Substitute(text_string, " ", "^", _ Len(text_string) - Len(.Substitute(text_string, " ", "")))) + 1, 256) End If End With End Function 

然后我可以指定哪个字进入哪个列(例如get_word(j2, 4) )。

不幸的是我碰到了一个障碍,如果一个特定的单词是它的单元格中的最后一个单词,它将不会被提取,除非我指定(例如get_word(j2, "Last") )。 这样做很棘手,意味着我将不得不单独通过单元格。

我真的很想知道是否有任何方法可以更改上面的VBA脚本,以便在Excel中可以指定我需要第4个单词或“最后一个”单词(如果是这样的话)。

你可以尝试这样的事情:

 Function Get_Word(text_string As String, nth_word) As String Dim vWords Dim lWordCount As Long vWords = Split(text_string, " ") lWordCount = UBound(vWords) + 1 If IsNumeric(nth_word) Then If nth_word < 1 Then nth_word = 1 If nth_word > lWordCount Then nth_word = lWordCount Get_Word = vWords(nth_word - 1) ElseIf nth_word = "First" Then Get_Word = vWords(0) ElseIf nth_word = "Last" Then Get_Word = vWords(lWordCount - 1) End If End Function 

如果你通过太大的价值,如果你什么都不想回来:

 Function Get_Word(text_string As String, nth_word) As String Dim vWords Dim lWordCount As Long vWords = Split(text_string, " ") lWordCount = UBound(vWords) + 1 If IsNumeric(nth_word) Then If nth_word > lWordCount Then Get_Word = "" Else If nth_word < 1 Then nth_word = 1 Get_Word = vWords(nth_word - 1) End If ElseIf nth_word = "First" Then Get_Word = vWords(0) ElseIf nth_word = "Last" Then Get_Word = vWords(lWordCount - 1) End If End Function 

如果你愿意,你仍然可以使用= Get_Word(A1,“Last”),但是如果你使用= Get_Word(A1,3)并且只有两个单词,你会得到一个空string。