简体   繁体   中英

EXCEL VBA: extracting 8 digits sequence from a string in cell

Good day everyone,

I am trying to find a smart solution of extracting 8 digits from a cell (unique ID). The problem here occurs that it might look like this:

112, 65478411, sale
746, id65478411, sale 12.50
999, 65478411
999, id65478411

Thats most of the cases, and probably all mentioned, so I basically need to find the 8 digits in the cell and extract them into different cell. Does anyone have any ideas? I though of eliminating the first characted, then check if the cell is starting with the id, eliminate it further but I understood that this is not the smart way..

Thank you for the insights.

Try this formula:

=--TEXT(LOOKUP(10^8,MID(SUBSTITUTE(A1," ","x"),ROW(INDIRECT("1:"&LEN(A1)-7)),8)+0),"00000000")

This will return the 8 digit number in the string.

To return just the text then:

=TEXT(LOOKUP(10^8,MID(SUBSTITUTE(A1," ","x"),ROW(INDIRECT("1:"&LEN(A1)-7)),8)+0),"00000000")

You can also write a UDF to accomplish this task, example below

Public Function GetMy8Digits(cell As Range)
Dim s As String
Dim i As Integer
Dim answer
Dim counter As Integer

'get cell value
s = cell.Value

'set the counter
counter = 0
'loop through the entire string
For i = 1 To Len(s)
    'check to see if the character is a numeric one
    If IsNumeric(Mid(s, i, 1)) = True Then
        'add it to the answer
        answer = answer + Mid(s, i, 1)
        counter = counter + 1
        'check to see if we have reached 8 digits
        If counter = 8 Then
            GetMy8Digits = answer
            Exit Function
        End If
     Else
     'was not numeric so reset counter and answer
     counter = 0
     answer = ""
    End If
Next i
End Function

Here is an alternative:

=RIGHT(TRIM(MID(SUBSTITUTE(A1,",",REPT(" ",LEN(A1))),LEN(A4),LEN(A1))),8)

Replace all commas with spaces repeated the length of the string,

Then take the mid point starting from the length of the original string for the length of the string (ie second word in new string)

Trim out the spaces

take the right 8 chars to trim out any extra chars (like id)

如何从句子中提取 8 个字母的单词,单元格 A1 中的例句是 WO# 000000.0 for ITSHTJ in Q0 20000_ITAI0006:TBD Replacement PO,我想提取 ITAI0006。

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