我正在使用一小段代码从一个单元格中取出名称并将它们分成单独的单元格。名称的数量差异很大,因此我需要尽可能地自动化它。
我正在使用以下宏:
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个字或者#34; last"如果是这样的话。
答案 0 :(得分: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,“Last”),但是如果你使用= Get_Word(A1,3)并且只有2个单词,你将得到一个空字符串。