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

时间:2015-06-17 09:36:05

标签: regex vba excel-vba user-defined-functions udf

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

WP0053

WP053

WP_053

WP_0053

WP 053

WP 0053

MDC_308

WP6

WP6.1

MDC_0308

请参阅以下预期输出图片;

enter image description here

非常感谢任何帮助

3 个答案:

答案 0 :(得分:0)

如果您的代码没有空格,则以下代码将有所帮助。

子测试()

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)

End Sub

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

例如: data =“A850085_WPC-MD-01003_SRI第2阶段 - 项目经理 - Dionysios Psachoulias”

然后结果将是 result =“WPC-MD-01003”

答案 1 :(得分:0)

尝试以下方面: -

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

答案 2 :(得分:0)

Public Function 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)

结束功能

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