简体   繁体   中英

Extract range from string

I have a report that exports to multiple Excel sheets. The first row on each sheet has a similar statement to the below.

Paste Data in range A1:K44 only. Data to come from "History" dump in Part Inquire.

I need to extract the range from that string. I've tried to use the split and find functions, but the length of the range changes (ie A1:AB53 , A15:C20 , etc.).

I welcome any input as to how to extract the range.

Just use Split() to split your string into an array and then grab the 5th element (index = 4):

Const SOME_TEXT As String = "Paste Data in range A1:K44 only. Data to come from ""History"" dump in Part Inquire."

Dim strRange As String
strRange = Split(SOME_TEXT)(4)

Debug.Print strRange

Output:

A1:K44

If the text that appears isn't quite so consistent, you can use a regex to extract the first range that appears within your string:

Const SOME_TEXT As String = "This string has A1:K44 in it but is inconsistent with the rest."

Dim re
Set re = CreateObject("VBScript.RegExp")
re.Pattern = "\b[A-Z]{1,3}\d+:[A-Z]{1,3}\d+\b"

If re.Test(SOME_TEXT) Then
    Debug.Print re.Execute(SOME_TEXT)(0)
End If

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM