2014-06-10 101 views
0

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

我使用下面的宏:

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个单词或“最后”单词(如果是这种情况)。

回答

1

你可以尝试这样的事:

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, “最后” )如果你想,但是如果你使用= Get_Word(A1,3)并且只有2个单词,你会得到一个空字符串。

+0

+1虽然'ElseIf nth_word =“第一个”'是相当多余的! (我正在考虑'nth_word = 1'。) –

+0

我认为原来有这个选项,它可能已经在公式中使用,所以... – Rory

+0

非常感谢。这是太棒了。 –

相关问题