Excel VBA,如何从几行句子中提取第n个单词



如何从几行句子中提取第n个单词?例如,我有一个句子在A1列,另一个在A2、A3列,以此类推,我如何从每个句子中提取第二个单词?并显示在每个句子旁边的单元格中。如果有人能为此写一个例子,我将不胜感激。

拆分它;

'//get value
dim para As string: para = range("a1").value
'//normalize new lines to space & split on space
dim words() As string
words = Split(Replace$(para, vbCrLf, " "), " ")
'//3rd word in adjacent cell;
range("b1").value=words(2)

您可以在VBA中轻松完成此操作,但我认为您希望使用"公式"来完成此操作。

以下是如何将其分解。将单元格A1视为具有要从中提取第二个单词的字符串。您可以使用查找功能来确定第二个单词的起始位置:

=FIND(" ", A1, 1)

同样的功能可以用来找出第二个单词的结尾:

=FIND(" ",A1, FIND(" ",A1)+1)

现在,我们可以使用Mid函数从单词的开始和结束位置提取单词:

=MID(A1, FIND(" ", A1, 1), FIND(" ",A1, FIND(" ",A1)+1)-FIND(" ", A1, 1))

这个最后的公式就是你想要使用的。它看起来很复杂,但它只是复制到Mid函数中的前两个公式。

我希望这能有所帮助。

您可以将其粘贴到UDF的VBA模块中,但仅适用于单个单元格。只需给它一个单元格引用和你想让它提取的单词编号:

Function WordExtract(CellRef As Range, Wordnum As Integer)
    Dim StartPos As Integer, EndPos As Integer, Counter As Integer
    StartPos = 1
    For i = 1 To Len(CellRef)
        If Mid(CellRef, i, 1) = " " Then
            If Wordnum - Counter = 1 Then
                EndPos = i - StartPos
                Exit For
                Else:
                StartPos = i + 1
                Counter = Counter + 1
            End If
        End If
    Next i
    If EndPos = 0 Then EndPos = Len(CellRef)
    WordExtract = Mid(CellRef, StartPos, EndPos)
End Function

最新更新