从句子中提取字母数字

时间:2017-06-21 13:37:08

标签: excel vba excel-vba

我想让VBA从作为句子的列G中提取字母数字值。

这句话通常是评论。所以它包括字符和数字。

该值始终以AI0开头,以0结尾。这可以是11到13位数。有时,评论中会将该数字称为AI038537500,有时也称为AI038593790000

我已经研究了几乎所有的网站,但没有发现这样的情况。我知道公式leftrightmid,但就我而言,它并不适用。

If you notice, here i have in comment section the Id with AI0 and Ends with 0. I want to extract this ID to result column.

任何领先都会很明显。

3 个答案:

答案 0 :(得分:2)

您可以尝试这样的事情......

将以下用户定义函数放在标准模块上,然后在表格中使用它,如

=GetAlphaNumericCode(A1)

<强> UDF:

Function GetAlphaNumericCode(rng As Range)
Dim Num As Long
Dim RE As Object, Matches As Object
Set RE = CreateObject("VBScript.RegExp")
With RE
   .Global = False
   .Pattern = "AI\d{9,}0"
End With
If RE.Test(rng.Value) Then
   Set Matches = RE.Execute(rng.Value)
   GetAlphaNumericCode = Matches(0)
Else
   GetAlphaNumericCode = "-"
End If
End Function

enter image description here

答案 1 :(得分:1)

为什么不试试下面这样的东西?

Sub findMatches()

    Dim strLength As Integer
    Dim i As Long

    For i = 1 To Rows.Count

        Dim AllWords As Variant
        AllWords = Split(Cells(i, 7).Value, " ")

        For Each Item In AllWords


            strLength = Len(Item)
            If strLength > 0 And strLength <= 13 And Item Like "A10*?#" Then
                Cells(i, 8) = Item
            End If

        Next

    Next i

End Sub

测试用例:

  1. 我是苹果,我的批号是:A10545440因此你需要知道
  2. 结果: A10545440

    1. 一些随机评论...... A20548650
    2. 结果: 无结果

      1. A101234567891是一个很棒的字母数字组合
      2. 结果:A101234567891

        1. 另一个随机评论... A10555
        2. 结果: A10555

          注意:上面的示例涵盖了以A10开头的字母数字组合的情况:

          • 在句子的中间,或
          • 句子的开头,或
          • 在句子结尾处

          另请注意:现在它设置为遍历所有行...因此,如果要限制它,请将Rows.Count语句中的For更改为您设置的限制。

          修改 在上面的代码中,我明确要求它查看G列

答案 2 :(得分:0)

你能尝试一下吗?我认为它应该完成这项工作,你也应该用列值修改代码,我用C列中的注释测试它,而代码将写在D列。

Option Explicit

    Sub FindValue()
    Dim i As Long
    Dim lastrow As Long
    Dim lFirstChr As Long
    Dim lLastChr As Long
    Dim CodeName As String

    lastrow = activesheet.Range("c" & Rows.Count).End(xlUp).Row
    ' gets the last row with data in it

    For i = 1 To lastrow
    ' shuffles through all cell in data

    lFirstChr = InStr(1, Cells(i, 3), "A10") ' gets the coordinate of the first instance of "A10"

    If lFirstChr = 0 Then GoTo NextIteration

    lLastChr = InStr(lFirstChr, Cells(i, 3), " ") ' gets the coordinate of the first instansce of space after "A10"

      If lLastChr = 0 Then 'if there is no space after A10 then sets lastchr to the lenght of the string

            lLastChr = Len(Cells(i, 3))

        End If

    CodeName = Mid(Cells(i, 3).Value, lFirstChr, lLastChr - lFirstChr) ' extracts the codename from the string value

    Range("d" & i).Value = CodeName

    Goto NextTteration


    NextIteration:
       Next i

    End Sub