string - 使用 Excel-VBA 从字符串中提取 5 位数字

标签 string vba excel numbers

作为非开发人员,我遇到了一个问题。我在 Excel 中有一列包含这样的信息:

46843 xxxx xxx x 

xxxx 65483 xxxx

xxxx xxx 65432 xxxxx 4 xx

“x”是普通字符。

我想要的是只能提取五位数字。 我开始了这样的事情但是很难放置一个循环以便它扫描所有字符串:

Function test()
val_in = "rue 4 qsdqsd CURIE 38320 EYBENS"
Filte = Left(val_in, 5)
If IsNumeric(Filte) Then
    test = Left(val_in, 5)
Else
    sp1 = InStr(1, val_in, " ")
    sp2 = InStr(sp1 + 1, val_in, " ")
    spt = sp2 + sp1

    If spt > 5 Then
        extr = Mid(val_in, spt, 5)
    End If
End If
End Function

如何将“Else”之后的部分变成一个循环,以便它扫描字符串的每个空格并仅提取包含 5 位数字的数字?

最佳答案

使用正则表达式

Option Explicit
Public Function GetNumbers(ByVal rng As Range) As Variant
    Dim arr() As String, i As Long, matches As Object, re As Object
    Set re = CreateObject("VBScript.RegExp")
    With re
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = "\b\d{5}\b"

        If .test(rng.Value) Then
            Set matches = .Execute(rng.Value)

            ReDim arr(0 To matches.Count - 1)
            For i = LBound(arr) To UBound(arr)
                arr(i) = matches(i)
            Next i

        Else
            arr(i) = rng.Value
        End If
    End With
     GetNumbers = Join(arr, ",")
End Function

数据:

Data


如果有多个匹配,则返回逗号分隔的列表。

关于string - 使用 Excel-VBA 从字符串中提取 5 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51590708/

相关文章:

C - 主要参数的输出反转

php - 简单的字符串替换字符

arrays - 在VBA中声明数组变量

c++ - 为什么 std::string 空代表是这样的?

c++ - 正则表达式作为标记器 - 以分隔符开头的字符串

vba - 从 PowerPoint 导出到动画 gif?

vba - Excel 根据用户更改范围中的另一个单元格来更新范围中的单元格值

excel - 如何在我的 excel 公式中自动更改部分数据

excel - 在 Team Build 2010 下针对 Excel 运行单元测试时出现异常

excel - Activeworkbook - 错误 91 - 对象变量或未设置 block 变量 - 在 Workbook_open