首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从句子中提取字母数字

从句子中提取字母数字
EN

Stack Overflow用户
提问于 2017-06-21 13:37:08
回答 3查看 293关注 0票数 1

我希望有一个VBA从G列中提取字母数字值,这是一个句子。

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

该值总是以AI0开头,以0结尾。这可能有11到13位长。在注释中,这个数字有时被提到为AI038537500,有时也被称为AI038593790000

我已经调查了几乎所有的网站,但没有发现任何这样的案例。我知道公式,leftrightmid,但在我的例子中,它不适用。

任何线索都是有价值的。

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-06-21 14:17:17

为什么不试一试呢?

代码语言:javascript
运行
复制
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,以防万一你需要知道

结果: A10545440

  1. 一些随机评论…A20548650

结果:无结果

  1. A101234567891是一个很棒的字母数字组合。

结果: A101234567891

  1. 另一个随机评论…A10555

结果: A10555

注意:上面的示例涵盖了字母数字组合(从A10开始)为以下两种情况:

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

注意:现在它被设置为遍历所有的行.因此,如果要限制这一点,请将For语句中的For更改为设置限制的任何内容。

编辑:在上面的代码中,我明确要求它在G列中查找

票数 1
EN

Stack Overflow用户

发布于 2017-06-21 14:39:55

你可以试试这样的..。

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

代码语言:javascript
运行
复制
=GetAlphaNumericCode(A1)

UDF:

代码语言:javascript
运行
复制
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

票数 2
EN

Stack Overflow用户

发布于 2017-06-21 14:14:16

你能试试这个吗?我认为它应该做好这项工作,你也应该用列值来修正代码,我用C列中的注释来测试它,而代码将用D列来编写。

代码语言:javascript
运行
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/44677755

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档