簡體   English   中英

提取特定單詞后的文本

[英]Extract text after specific word

我想在字符串中的“for”一詞之后立即檢索文本。 在下面的示例中,我想檢索“GLDSK8716”。

GLDSK8716 - 衍生合約 - 期貨、遠期、掉期和期權的完成通知

我試過這個公式,但它檢索“for”之后的所有文本。

=TRIM(MID(R2,SEARCH("For",R2)+LEN("for"),255))

這是我的 VBA 版本:

Option Explicit

Public Function ExtractAfterWord(rngWord As Range, strWord As String) As String

    On Error GoTo ExtractAfterWord_Error

    Application.Volatile

    Dim lngStart        As Long
    Dim lngEnd          As Long

    lngStart = InStr(1, rngWord, strWord)
    If lngStart = 0 Then
        ExtractAfterWord = "Not Found"
        Exit Function
    End If
    lngEnd = InStr(lngStart + Len(strWord) + 1, rngWord, " ")

    If lngEnd = 0 Then lngEnd = Len(rngWord)

    ExtractAfterWord = Trim(Mid(rngWord, lngStart + Len(strWord), lngEnd - lngStart - 2))



    On Error GoTo 0
    Exit Function

ExtractAfterWord_Error:

    ExtractAfterWord = Err.Description

End Function

代碼中的條件( if lngEnd = 0 )是為了確保即使 for 位於文本中的最后一個單詞之前,公式也能正常工作。 還添加了“未找到”答案。

在此處輸入圖片說明

試試=MID(A1,FIND("for ",A1)+4,FIND(" ",A1,FIND("for ",A1)+4)-(FIND("for ",A1)+4))

假設您的文本在單元格 A1 中並且模式for <data> -

我的解決方案是在 VBA 中。 下面的代碼使用RegEx查找空格之間的所有單詞。 然后它遍歷所有單詞,一旦找到“for”,它就會引發一個標志以指示下一個單詞( RegEx.Match )是您要查找的單詞。

代碼

Option Explicit

Sub ExtractNumbers()

Dim Reg1 As Object
Dim RegMatches As Variant
Dim Match As Variant
Dim NextWord As Boolean

Set Reg1 = CreateObject("VBScript.RegExp")
With Reg1
    .Global = True
    .IgnoreCase = True
    .Pattern = "\w{1,50}" ' Match any set of characters up to length of 50, untill a space
End With

Set RegMatches = Reg1.Execute(Range("R2").Value)
NextWord = False ' <-- reset flag
If RegMatches.Count >= 1 Then        
    For Each Match In RegMatches
        If NextWord Then
            MsgBox "The word you are looking for is '" & Match & "'"
            Exit Sub
        End If
        If UCase(Match) Like "FOR" Then NextWord = True '<-- "for" found >> raise flag up
    Next Match
End If

End Sub

Cell R2 中字符串的屏幕截圖並生成MsgBox

在此處輸入圖片說明

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM