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虽然'ElseIf nth_word =“第一个”'是相当多余的! (我正在考虑'nth_word = 1'。) –
我认为原来有这个选项,它可能已经在公式中使用,所以... – Rory
非常感谢。这是太棒了。 –