简体   繁体   English

EXCEL VBA:从单元格中的字符串中提取8位数字序列

[英]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).我正在尝试找到从单元格(唯一 ID)中提取 8 位数字的智能解决方案。 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.这就是大多数情况,可能都提到过,所以我基本上需要找到单元格中的 8 位数字并将它们提取到不同的单元格中。 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..我虽然消除了第一个字符,然后检查单元格是否以 id 开头,进一步消除它,但我明白这不是聪明的方法..

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. 这将返回字符串中的8位数字。

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 您还可以编写一个UDF来完成此任务,例如下面的示例

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个字符以修剪掉多余的字符(例如id)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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