Извлечение текста между разделителями в VBA с примерами кода

Фраза «Текст VBA между» относится к поиску и извлечению текста, расположенного между определенными разделителями или ключевыми словами в коде VBA (Visual Basic для приложений). Вот несколько методов с примерами кода для достижения этой цели:

Метод 1: использование функций InStr и Mid

Sub ExtractTextBetween()
    Dim inputText As String
    Dim startText As String
    Dim endText As String
    Dim startPos As Integer
    Dim endPos As Integer
    Dim extractedText As String

    ' Input text containing the target text
    inputText = "This is some text between the start and end markers."

    ' Start and end markers
    startText = "start"
    endText = "end"

    ' Find the positions of start and end markers
    startPos = InStr(1, inputText, startText) + Len(startText)
    endPos = InStr(startPos, inputText, endText)

    ' Extract the text between the markers
    extractedText = Mid(inputText, startPos, endPos - startPos)

    ' Display the extracted text
    MsgBox extractedText
End Sub

Метод 2: использование регулярных выражений

Sub ExtractTextBetweenRegex()
    Dim inputText As String
    Dim startRegex As Object
    Dim endRegex As Object
    Dim matchStart As Object
    Dim matchEnd As Object
    Dim extractedText As String

    ' Input text containing the target text
    inputText = "This is some text between the start and end markers."

    ' Regular expressions for start and end markers
    Set startRegex = CreateObject("VBScript.RegExp")
    Set endRegex = CreateObject("VBScript.RegExp")

    startRegex.Pattern = "(?<=start).*"
    endRegex.Pattern = ".*(?=end)"

    ' Find the matches for start and end markers
    Set matchStart = startRegex.Execute(inputText)
    Set matchEnd = endRegex.Execute(inputText)

    ' Extract the text between the markers
    extractedText = matchStart(0) & matchEnd(0)

    ' Display the extracted text
    MsgBox extractedText
End Sub

Метод 3. Использование функции разделения

Sub ExtractTextBetweenSplit()
    Dim inputText As String
    Dim startText As String
    Dim endText As String
    Dim textArray() As String
    Dim extractedText As String

    ' Input text containing the target text
    inputText = "This is some text between the start and end markers."

    ' Start and end markers
    startText = "start"
    endText = "end"

    ' Split the text using start and end markers
    textArray = Split(inputText, startText)

    ' Extract the text between the markers
    extractedText = Split(textArray(1), endText)(0)

    ' Display the extracted text
    MsgBox extractedText
End Sub