首页 > 解决方案 > 如何提取列中的特定数据并使用 VBA 在另一列中解析它

问题描述

我有一些麻烦来解决这个问题

所以我的目标是提取列中的特定信息并将其解析到另一列,如下所示

在此处输入图像描述

你能帮我看看vba代码吗

B列=数据

D列=我想得到的结果

附上作业本

亲切的问候,

标签: excelvba

解决方案


使用正则表达式。如果有多个,这只会找到第一个实例。

Option Explicit

Sub RegexMatch()

    Dim wb As Workbook, ws As Worksheet, cell As Range
    Dim lastRow As Long, r As Long, s As String

   ' build regex pattern
    Dim regex As Object, m As Object
    Set regex = CreateObject("vbscript.regexp")
    With regex
       .Global = False
       .MultiLine = False
       .IgnoreCase = True
       .Pattern = "([A-Z]{2}\d{9})" ' pattern AZ123456789
    End With

    ' data
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("Sheet1")
    lastRow = ws.Cells(Rows.Count, "B").End(xlUp).Row

    For Each cell In ws.Range("B1").Resize(lastRow)
        s = cell.Value
        If regex.test(s) Then
            Set m = regex.Execute(s) '
            cell.Offset(0, 2) = m(0) ' matched term  in col D
        End If
    Next

    MsgBox lastRow & " rows parsed", vbInformation
End Sub

推荐阅读