A Regular Expression can be used.
Code
Dim texto As String
Dim objCorresp As Object, objExpReg As Object
Set objExpReg = CreateObject("VBScript.RegExp")
'Expressão Regular
With objExpReg
.Pattern = "nome:[\s\S]+?(?=e-mail)"
.Global = True
.MultiLine = True
.IgnoreCase = True
End With
texto = "Bla bla bla bla bla NOME: JOSH IDNUMBER: 098766 E-MAIL: [email protected] bla bla bla."
Set objCorresp = objExpReg.Execute(texto)
If objCorresp.Count <> 0 Then
For Each c In objCorresp
Debug.Print Trim(c)
Next c
End If
Result
For the code example, the result is: NOME: JOSH IDNUMBER: 098766
For a multi-line string:
texto = "Bla bla bla bla bla NOME: JOSH IDNUMBER: 098766 E-MAIL: [email protected] bla bla bla." & vbNewLine & _
"Bla bla bla bla bla NOME: JOAO IDNUMBER: 098766 E-MAIL: [email protected] bla bla bla."
The result is:
NOME: JOSH IDNUMBER: 098766
NOME: JOAO IDNUMBER: 098766
Regular Expression
The following expression can be used: nome:[\s\S]+?(?=e-mail)
In this expression it captures text that starts with nome:
and is followed by any character with lazy quantizer [\s\S]+?
, before e-mail (?=e-mail)
And the demo can be viewed at this link
Enable Regex in Excel
RegEx needs to be enabled, Enable Developer mode
In the 'Developer' tab, click 'Visual Basic' and the VBA window will open.
Go to 'Tools' - > 'References ...' and a window will open.
Look for 'Microsoft VBScript Regular Expressions 5.5', as in the image below. And enable this option.
UserDefinedFunction
AUDFcanbecreatedwiththefollowingcode:
Functionextrair_texto_entre(inicioAsString,fimAsString,texto)AsStringDimobjCorrespAsObject,objExpRegAsObjectSetobjExpReg=CreateObject("VBScript.RegExp")
'Expressão Regular
With objExpReg
.Pattern = inicio & "[\s\S]+?(?=" & fim & ")"
.Global = True
.MultiLine = True
.IgnoreCase = True
End With
Set objCorresp = objExpReg.Execute(texto)
If objCorresp.Count <> 0 Then
For Each c In objCorresp
extrair_texto_entre = Trim(c)
Next c
End If
End Function
Result
This function can be used in the Worksheet as follows:
=extrair_texto_entre("string de início"; "string de fim"; célula ou "string")
In that it can be used or referenced by a cell or by entering a String.
With string
In it, you use the function as follows:
=extrair_texto_entre("nome:";"e-mail";"Bla bla bla bla bla NOME: JOSH IDNUMBER: 098766 E-MAIL: [email protected] bla bla bla.")
And you get the following result: NOME: JOSH IDNUMBER: 098766
Withcell
Inthiswayyouinsertthefunctionintotheworksheetasfollows:
=extrair_texto_entre("nome:";"e-mail";B2)
And you get the result:
NOME: JOSH IDNUMBER: 098766