提取以相同的两个字符开头并以数字字符结尾的文本

Extract text which begin with the same two characters and end in a numeric character

我想从更大的文本提取中提取代码,我拥有的常量是代码将以 WP 或 MD 开头并以数值结尾,代码可以包含的模式示例是下面;

WP0053

WP053

WP_053

WP_0053

WP 053

WP 0053

MDC_308

WP6

WP6.1

MDC_0308

请查看下面的预期输出图片;

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

如果您的代码没有 space 那么下面的代码会有所帮助。

子测试()

Data = "A850085_MDC-WP-01003_SRI Phase 2 - Programme Manager - Dionysios Psachoulias"

startpos = InStr(Data, "WP")
If startpos = 0 Then startpos = InStr(Data, "MD")

fisrtNumPos = 0
LastNumPos = 0
For i = startpos To Len(Data)

    If fisrtNumPos = 0 And LastNumPos = 0 Then
        If IsNumeric(Mid(Data, i, 1)) Then
            fisrtNumPos = i
        End If
    Else
        If Not IsNumeric(Mid(Data, i, 1)) Then
            LastNumPos = i
            Exit For
        End If
    End If
Next i

Endpos = LastNumPos - startpos

Debug.Print Mid(Data, startpos, Endpos)

结束子

现在应该可以了。但是如果文本包含 "MD" 后跟 "WP" 那么它将只从 WP 获取代码。

例如: 数据= "A850085_WPC-MD-01003_SRI Phase 2 - Programme Manager - Dionysios Psachoulias"

那么结果就是 结果= "WPC-MD-01003"

按照以下方式尝试:-

Dim cell
Dim tmp as string

For each cell in activesheet.columns(1).usedrange.cells
    If InStr(1, cell.Value, "_MDC_", vbTextCompare) > 0 Then
        tmp = Right(cell.Value, Len(cell.Value) - InStr(1, cell.Value, "_MDC_", vbTextCompare))
        tmp = Left(tmp, InStr(1, tmp, " ", vbTextCompare) - 1)
        cell.offset(0,2).value = tmp
    End If
next cell

Public 函数 GetCode(data As String) As String

startpos = InStr(data, "WP")
If startpos = 0 Then startpos = InStr(data, "MD")

fisrtNumPos = 0
For i = startpos To Len(data)

    If fisrtNumPos = 0 And LastNumPos = 0 Then
        If IsNumeric(Mid(data, i, 1)) Then
            fisrtNumPos = i
        End If
    Else
        If Not IsNumeric(Mid(data, i, 1)) Then
            LastNumPos = i
            Exit For
        End If
    End If
Next i

Endpos = LastNumPos - startpos

GetCode = Mid(data, startpos, Endpos)

结束函数

在任何模块中添加此代码并尝试。