如何通过 VBA 或 excel 公式从文本字符串中提取特定的字母和数字

How can I extract a specific Letter(s) and numbers from a text string via VBA Or excel Formula

我想从位于 excel 的列中的较大字符串中提取文本和数字的组合。

我必须使用的常量是每个文本字符串将

例如;

COB0012 WP0402 Electronic Payments - SME Consultancy
DCPY708 A850035 WP161 Configuration Manager Core General (Aman Ranjan) A614019 WP0302 SQL 2005 Upgrade Project – WFCopiesChq - Next Stage SUTP016 EPM Training T2

输出

COB0012
A850035
SUTP016

我了解标准的左/右/中/搜索功能,但是我的数据集变化很大,所以我想创建一些东西来自动化这个过程。 (1000 行)

我认为 UDF 函数可以解决问题,但我对 UDF 的了解非常基础。

如有任何帮助,我们将不胜感激。

考虑:

Public Function Xtractor(r As Range) As String
   Dim CH As String, L As Long
   ary = Split(r.Text, " ")
   For Each a In ary
      L = Len(a)
      CH = Left(a, 1)
      If L = 7 Then
         If CH = "S" Or CH = "A" Or CH = "C" Then
            Xtractor = a
            Exit Function
         End If
      End If
   Next a
   Xtractor = ""
End Function

@Gary's Student 变体但有一些差异

Public Function Xtractor(r As Range) As String
    Dim a, ary
    ary = Split(r.Text, " ")
    For Each a In ary
        If Len(a) = 7 And a Like "[SAC]*" Then
            Xtractor = a
            Exit Function
        End If
    Next a
End Function

输出

正则表达式将非常有效 - 特别是如果您将它与变体数组而不是范围结合使用。

Sub UseaRegex()
MsgBox StrChange("COB0012 WP0402 Electronic Payments - SME Consultancy [I would require COB0012]")
MsgBox StrChange("DCPY708 A850035 WP161 Configuration Manager Core General (Aman Ranjan)")
End Sub

函数

Function StrChange(strIn As String) As String
Dim objRegex As Object
Set objRegex = CreateObject("vbscript.regexp")
With objRegex
    .Pattern = "[ACS]\w{6}"
     If .test(strIn) Then
        StrChange = .Execute(strIn)(0)
     Else
        StrChange = "No match"
     End If
End With
End Function